Delegates and Event

  • Thread starter Thread starter NotYetaNurd
  • Start date Start date
N

NotYetaNurd

Hi all,
I am really confused about delegates and events can you ppl give me the
difference between these...

Regards,
....
 
Delegates are the prototype of the function that will be called when an event is raised. Think
of it as a function pointer if you are familiar with C++.

Delegate -=> public delegate void MyDelegate(object sender, System.EventArgs e)

Some function -=> public void myfoo (object sender, System.EventArgs e) { ...Do something...}

instantiation of Delegate -=> MyDelegate mydel += new MyDelegate(myfoo);

You can add many functions to the instatiated delegate by using +=

You can call the delegate directly as if it were a function.
mydel (this, null);

Each function added to will be called in succession.

===================================

Events are generated based on some condition such as a button click or you have
withdrawn too much money out of your bank account.

Event -=> public event MyDelegate myevent;

Generate event -=> myevent ( this, null);

====================================

The main difference between the two is that there may be MANY instances of of MyDelegate
scattered through many difference source files.
MyDelegate mydel_1 += new MyDelegate(myfoo_1); inside class MyClass_1
MyDelegate mydel_2 += new MyDelegate(myfoo_2); inside class MyClass_2
MyDelegate mydel_3 += new MyDelegate(myfoo_3); inside class MyClass_3

If you use the call the delegate directly, you are doing just that. When you raise an event
it is received by ALL the implementations of the MyDelegate signature.

Cheers...
 
Back
Top