Difference between delegate and event
The following table lists the difference between the delegate and the event in C#.
Delegate | Event |
---|---|
A delegate is declared using the delegate keyword. | An event is declared using the event keyword. |
Delegate is a function pointer. It holds the reference of one or more methods at runtime. | The event is a notification mechanism that depends on delegates |
Delegate is independent and not dependent on events. | An event is dependent on a delegate and cannot be created without delegates. Event is a wrapper around delegate instance to prevent users of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list. |
Delegate includes Combine() and Remove() methods to add methods to the invocation list. | EventInfo class inspect events and to hook up event handlers that include methods AddEventHandler() and RemoveEventHandler() methods to add and remove methods to invocation list, respectively. |
A delegate can be passed as a method parameter. | An event is raised but cannot be passed as a method parameter. |
= operator is used to assigning a single method, and += operator is used to assign multiple methods to a delegate. | = operator cannot be used with events, and only += and -= operator can be used with an event that adds or remove event handler. These methods internally call AddEventHandler and RemoveEventHandler methods. |
In a way, an event is a delegate only. The program code will work even if you remove the event keyword and only use a delegate. However, using the event keyword, we prevent subscribers to register with an event by using = operator and thereby removing all handlers.
Consider the following example.
public delegate void Notify();
public Notify MyDelegate;
MyDelegate = MyMethod;// valid
MyDelegate += MyMethod;// valid
public delegate void Notify();
public event Notify MyEvent;
MyEvent = MyEventHandler;// Error
MyEvent += MyEventHandler;// valid