Delegate in C#

Delegates is a word that frequently pops up in interviews and many candidates become confused and nervous when they hear this word. In this article, I am trying to explain delegates in an easy to understand way, hopefully after going through this article, you will feel comfortable using delegates and answering any question related to delegates.

What is a delegate?
 
A Delegate is an object that can refer to a method.
 
When we are creating delegates, we are creating an object that can hold a reference to a method; it necessarily means that a delegate can invoke the method to which it refers. 
 
As the delegate refers to a method, the same delegates can be used to call multiple methods just by changing the method name at the run time; provided the method (instance or static) match the signature and return type.
 
Get my 500+ Web development .NET Tips & Tricks and available ASP.NET online training here.
 
Confused? Not a problem, just go through following code snippet of code behind (DelegatesPage .aspx.cs) of my DelegatesPage.aspx page.

public partial class DelegatesPage : System.Web.UI.Page

{

delegate int Add(int x);

protected void Page_Load(object sender, EventArgs e)

{

Add a = Sum;

Response.Write(a(6).ToString());

Response.Write("<br />");

a = Minus;

Response.Write(a(6).ToString());

}

int Sum(int a)

{

return a + a;

}

int Minus(int b)

{

return b - b;

}

}

In the preceding code snippet, we have declared a delegates named Add that accepts one parameter of integer type. In the Page_Load event, we are assigned the Sum method (we will define & implement this method later on) to the delegates object "a". That means that now "a" can be used to invoke the Sum method. In the very next line, we used "a" that is nothing but the object of the delegate Add to call the Sum method. As the Sum method accepts one parameter so we are calling "a" with one parameter "6".
 
Since the Sum method simply adds the values and returns the result, calling "a(6)" will return 12.
 
As I said earlier, the delegate simply refers to a method so the same delegate can be used to refer to another method and next I have referred Minus method (defined and implemented later on) and again we are calling the Minus method just by using the delegate object that gives 0 as the result.
 
What is Multicast delegates?

As the name (Multicast) suggests, it means multiple so a delegate that refers to multiple methods is called a Multicast delegate. Calling the object of the delegates automatically calls all the methods that refer to this delegate. These methods can be attached and detached using "+=" and "-=" to the instance of the delegate.
 
In case a delegate returns a value (as in the case of the above delegate), the value returned by the last method becomes the return value of the entire delegate invocation methods.

public partial class DelegatesPage : System.Web.UI.Page

{

// multi-cast delegates

delegate void Add(int x);

protected void Page_Load(object sender, EventArgs e)

{

Add a = Sum;

a += Minus;

a(6);

}

 

void Sum(int a)

{

Response.Write(a + a);

Response.Write("<br />");

}

 

void Minus(int b)

{

Response.Write(b - b);

}

}

In the preceding code snippet, as you can see we have a Delegate named "Add" that accepts two parameters but does not return a value since it is void.
 
In the Page_Load event, we have created the object of the delegate and assigned the Sum method; in the very next line we have attached one more method called Minus to the same delegates using the "+=" operator.
 
Now calling the delegates object simply executes both the Sum and Minus methods and gives corresponing results. So we will get the results 12 and 0.  If you have consumed WCF services, you must have encountered multicast delegates.
 
When to use Delegates?
 
All this looks fine, now the important question is why and when to use delegates? As per MSDN,
 
use a delegate when:

  • An eventing design pattern is used.

  • It is desirable to encapsulate a static method.

  • The caller has no need access other properties, methods, or interfaces on the object implementing the method.

  • Easy composition is desired.

  • A class may need more than one implementation of the method.

Sounds complicated? In simple terms Delegates are basically used in:

  1. Abstracting and encapsulating methods

  2. Callback mechanism

  3. Asynchronous programming

  4. Sequential programming etc.

Up Next
    Ebook Download
    View all
    Learn
    View all