Sunday, December 19, 2010

Delegates in C#

A Delegate in C# is a method that points to another method with same signature.

Think it as an expression which allows you to invoke any method whose signature matches to the signature of delegate itself.

In a real life programming example, suppose you have a button control and you have some code to be executed when this button is clicked. What if your Button control would have come with a specific method name, which only could be invoked when you click the button?
You could not change the name of the method and it would get worse when you have more than one similar Button controls on the form each demanding an event handler method.

The solution to this problem comes with delegates. You simply add a Click EventHandler to the button and assign a method which will be invoked when button is clicked.

More or less, it looks like this:
Button1.Click += new EventHandler(Button1_Click);

protected void Button1_Click(object sender, EventArgs e)
{
}

Click (in Button1.Click) is a delegate (of type EventHandler) defined for Button control which can invoke a method with void as return type and two arguments (object and EventArgs).

It doesn't care about the name of the method until you pass it to the constructor of EventHandler (new EventHandler(...)).

It means that if it would have been any method with return type void as return type and two arguments (object and EventArgs), you can invoke it on click event of Button control by delegating it to the Click Event of button.

Button was an example from inbuilt control library. It is already implemented with a delegate of type EventHandler defined as:
public delegate void EventHandler(object sender, EventArgs e);
The Button class defines an event of this type EventHandler as:
public event EventHandler Click;

So, when you need to call a method on click of this Button, you multicast the Click Event to your method by using += new ... expression. It means that you can assign more than one methods (with same signature as that of delegate) in the invocation list of the delegate. All of these methods will be invoked when this event is called.

So, delegates play an important role to allow the programmers to call any method (of delegate's signature) without knowing its name at design time.

Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.

There is a limited flexibility available in .NET with the signature of methods which are to be passed to delegates. In other words, methods don't need to match the delegate signature exactly. MSDN describes more on this.