A delegate is a way of telling C# which method to call when an event is triggered. For example, if you click a Button on a form, the program would call a specific method. It is this pointer that is a delegate. Delegates are good, as you can notify several methods that an event has occurred, if you wish so.
Delegates form the basis of event handling in C#.
A delegate declaration specifies a particular method signature. References to one or more methods can be added to a delegate instance.
Delegates types are declared with the delegate keyword. They can appear either on their own or nested within a class, as shown below.
namespace DelegateArticle
{
public delegate string FirstDelegate (int x);
public class Sample
{
public delegate void SecondDelegate (char a, char b);
}
}
There are three steps in defining and using delegates:
Declaration
Instantiation
Invocation
An event is a notification by the .NET framework that an action has occurred. Each event contains information about the specific event, e.g., a mouse click would say which mouse button was clicked where on the form.
Let's say you write a program reacting only to a Button click. Here is the sequence of events that occurs:
User presses the mouse button down over a button
The .NET framework raises a MouseDown event
User releases the mouse button
The .NET framework raises a MouseUp event
The .NET framework raises a MouseClick event
The .NET framework raises a Clicked event on the Button
Since the button's click event has been subscribed, the rest of the events are ignored by the program and your delegate tells the .NET framework which method to call, now that the event has been raised.
Differences Between Delegates and Events in C#
Delegate is an object used as a function pointer to hold the reference of a method. On the other hand, events provide an abstraction to delegates.
A keyword required to declare a delegate is a delegate whereas, a keyword required to declare an event is event.
A delegate is declared outside a class whereas, an event is declared inside a class.
To invoke a method using a delegate object, the method has to be referred to the delegate object. On the other hand, to invoke a method using an event object the method has to be referred to the event object.
Covariance and Contravariance provide extra flexibility to the delegate objects. On the other hand, event has no such concepts.
Event Accessor handles the list of event handlers whereas delegate has no such concept.
Delegates are independent on events but, events can not be created without delegate.