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.
 
Confused? Not a problem, just go through following code snippet of code behind (DelegatesPage .aspx.cs) of my DelegatesPage.aspx page.
  1. public partial class DelegatesPage : System.Web.UI.Page  
  2. {  
  3.     delegate int Add(int x);  
  4.     protected void Page_Load(object sender, EventArgs e)  
  5.     {  
  6.         Add a = Sum;  
  7.         Response.Write(a(6).ToString());  
  8.         Response.Write("<br />");  
  9.         a = Minus;  
  10.         Response.Write(a(6).ToString());  
  11.     }  
  12.     int Sum(int a)  
  13.     {  
  14.         return a + a;  
  15.     }  
  16.     int Minus(int b)  
  17.     {  
  18.         return b - b;  
  19.     }  
  20. }  
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.
  1. public partial class DelegatesPage : System.Web.UI.Page  
  2. {  
  3.     // multi-cast delegates  
  4.     delegate void Add(int x);  
  5.     protected void Page_Load(object sender, EventArgs e)  
  6.     {  
  7.         Add a = Sum;  
  8.         a += Minus;  
  9.         a(6);  
  10.     }  
  11.     void Sum(int a)  
  12.     {  
  13.         Response.Write(a + a);  
  14.         Response.Write("<br />");  
  15.     }  
  16.     void Minus(int b)  
  17.     {  
  18.         Response.Write(b - b);  
  19.     }  
  20. }  
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.


Similar Articles