जगदीश खोलिया: Difference between event and delegate

Monday, June 4, 2012

Difference between event and delegate

Class1 c = new Class1();
c.MyDeleageteCallback = new Class1.DomSomethingDelegate(this.Calculate);

This piece of code will work just fine with class1, but if we were to try to use it on class2, where there is the event keyword declared, we would get a compilation error.

In conclusion: an event declaration adds a layer of protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list, and only allows adding or removing targets from the invocation list.

Three main differences:
events can be included in interfaces
events can only be invoked by the containing class
events' signatures are constrained (depends on language and CLS compliance)


1) It is a data member of a type(class/structure)

2)It is declared inside a type(class/structure)

3) It is used to generate notifications which are then passed to methods though


1)It is a datatype(reference type) that holds references of methods with
some signatures.also called as function pointer.

2)It may or may not be declared inside a class.

3)It is used as the return type of an event and used in passing messages from event to methods.

example: 1
namespace dd
//delegate declaration
delegate void first();
class cc
//event declaration
public first myevent;

example 2:
button1.Click+=new EventHandler(this.button1_Click);

Click is the event that returns an instance of the EventHandler delegate.
EventHandler delegate has the reference of button1_Click event and that
helps in the communication betwen the Click event and button1_Click method.
Post a Comment