Delegate

  • Thread starter Thread starter Joanne
  • Start date Start date
J

Joanne

A delegate is said to be good for the programmer since it
provides a good way of invoking methods which are not
exactly known until run time.

What does "good" mean here?

If i declare myDelegate and associate some method with
it, am I not knowing which method will be executed?

Is the following code correct? I have the idea that the
delegate is not being properly associated with the event,
although the targeted method is invoked just fine.

//class members
delegate void handlerDelegate();
event handlerDelegate ON_a;

//note: outputText matches the delegate signature
this.ON_a += new MyClass.handlerDelegate
this.outputText);
//call the event
ON_a();
 
hi joanne,

your delegate an call seems (to me) to be correct. (just i don't know if you
can have a delegate inside a class, may be you can)
just verify if the event is full befor call the event
if(ON_a!=null) ON_a();

seems i do not help :p
ROM
 
A delegate is said to be good for the programmer since it
provides a good way of invoking methods which are not
exactly known until run time.

What does "good" mean here?

it surely means "safe".

think of delegates as of "type-safe function pointers". even the declaration
is similar:

typedef int (*pf)(int); // C-style function pointer
delegate int pf(int n); // C#-style delegate

the difference is clearly visible while you create an instance of the
function pointer:

// C-style cast will always succeed...
pf f = (pf)GetProcAddress(...);
// ...so the call can cause severe problems if wrong signature is used
int a = f(5);

// C#-style delegate creation will raise an exception if the signatures are
different...
pf f = new pf( ... );
// ...so the call is always safe
int a = f(5);

regards,
Wiktor
 
Back
Top