The following table lists the difference between the delegate and the event in C#.
|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
- Difference between Array and ArrayList
- Difference between Hashtable and Dictionary
- How to write file using StreamWriter in C#?
- How to sort the generic SortedList in the descending order?
- How to read file using StreamReader in C#?
- How to calculate the code execution time in C#?
- Design Principle vs Design Pattern
- How to convert string to int in C#?
- Boxing and Unboxing in C#
- out keyword in C#
- Query geolocation & proxy data in .NET using IP2Location
- ref Keyword in C#
- How to sort an array in C#?
- How to sort object array by specific property in C#?
- How to get a comma separated string from an array in C#?
- How to remove duplicate values from an array in C#?
- How to combine two arrays without duplicate values in C#?
- Difference between String and string in C#.
- How to count elements in C# array?
- Compare strings in C#