Delegates In C#

Introduction

 
A delegate is a reference type variable whose objects can refer to multiple methods which can then be invoked later. Instead of calling methods directly, delegates can be used to call these methods. 
 

Delegate

 
A delegate is a type safe and object oriented object that can point to another method or multiple methods which can then be invoked later. It is a reference type variable that refers to methods. It is the C# equivalent of a function pointer in c/c++. A delegate maintains three important pieces of information which are as follows:
  • Name of the method on which it has to make calls.
  • Any argument of the method.
  • The return value if any.
Syntax to declare a delegate
 
[modifier] delegate [return_type] [delegate_name]([parameter_list]);
 
In the above mentioned syntax each keyword has a separate meaning which is as follows,
  • Modifier defines the access of the delegate.
  • delegate is a keyword which is used to define a delegate.
  • return_type specifies the type of value to be returned by the method, to which the delegate will make a call.
  • delegate_name specifies the name of delegate as defined by the user.
  • parameter_list specifies the list of parameters as required by those methods to which the delegate will make a call.
Upon delegate declaration, the instance of the delegate can point to those methods which are having the same return type and same number of parameters as that of a defined delegate.
 
For example, let's declare a  delegate of integer type having public access specifier and which contains two parameters of integer type.
 
public delegate int Delegate1(int x, int y)
 
This particular delegate can point to any method that takes in  two integers as parameters and returns an integer. So this delegate can only point to methods having similar signatures as that of a delegate.
 
Let's assume, we have a class that contains methods that a particular delegate will point to as in the below code snippet.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. namespace Delegate  
  5. {  
  6.     public delegate int SampleDelegate(int x, int y);  
  7.   
  8.     public class NumberClass  
  9.     {  
  10.         public static int Add(int x, int y)  
  11.         {  
  12.             return (x + y);  
  13.         }  
  14.   
  15.         public static int Multiply(int x, int y)  
  16.         {  
  17.             return (x * y);  
  18.         }  
  19.   
  20.     }  
  21.     class Program  
  22.     {  
  23.         static void Main(string[] args)  
  24.         {  
  25.             //first needs to instantiate the delegate named sampledelegate  
  26.             SampleDelegate del1 = new SampleDelegate(NumberClass.Add);//now it will point to numberclass.add  
  27.             int addresult = del1(5, 5);  
  28.             Console.WriteLine("5+5=" + addresult);  
  29.   
  30.             SampleDelegate del2 = new SampleDelegate(NumberClass.Multiply);//now it will point to numberclass.add  
  31.             int multiresult = del2(5, 5);  
  32.             Console.WriteLine("5*5=" + multiresult);  
  33.         }  
  34.     }  
  35. }  
Output
 
Delegates In C#
 
In the above code, we are defining a delegate named SampleDelegate which is of integer type having public access specifier and contains two parameters of integer type.
 
After declaring the delegate, we are creating a class named NumberClass which contains two methods, Add() and Multiply(). These methods are returning an integer type value.
 
Inside Main() function, we have created an instance of delegate called del1 that points to functions inside the class named MyClass.    
 
So inside the main function, we can create two instances of the delegate named SampleDelegate as follows,
  1. Delegate1 del1 = new MyDelegate(MyClass.Add);  
  2. Delegate1 del2 = new MyDelegate(MyClass.Multiply);   
If we want to invoke this add  and multiply method, that is call these methods, we can make use of delegate which will point to these methods and call them as follows
  1. Int result = del1(5,5);  
  2. Int multiresult = del2(5,5);   
So instead of calling these methods directly, delegates can be used to call these methods.
 
Every delegate needs to point or subscribe to some method in some class and it has to follow the same signature rules. If signature rules are not followed, then the delegate will not be able to point to that method.
 

Multicasting in Delegates

 
Delegates have the ability to multicast. A delegate object can maintain a list of methods to call rather than just one single method. So we can subscribe as many methods to delegate as we want.
 
We can have one delegate pointing to multiple functions having the same signature as that of the delegate. Delegates have the ability to multicast which means a delegate object can maintain a list of methods to call rather than just one single method.
 
If we want to add a method to the invocation list of delegate object, then we can use += operator for subscribing to more than one method. If we want to remove a method from an invocation list of delegate objects, then we can use -= operator to unsubscribe a method.
  1. using System;  
  2.   
  3. namespace MultiCasting  
  4. {  
  5.     public delegate void MulticastDelegate(int x, int y);  
  6.   
  7.     public class Multi  
  8.     {  
  9.         public static void Add(int x, int y)  
  10.         {  
  11.             Console.WriteLine("you are in the add method.");  
  12.             Console.WriteLine(x + "+" + y + "=" + (x + y));  
  13.         }  
  14.         public static void Multiply(int x, int y)  
  15.         {  
  16.             Console.WriteLine("you are in the multiplication method.");  
  17.   
  18.             Console.WriteLine(x + "*" + y + "=" + (x * y));  
  19.   
  20.         }  
  21.   
  22.           
  23.     }  
  24.     class Program  
  25.     {  
  26.         static void Main(string[] args)  
  27.         {  
  28.             MulticastDelegate del1 = new MulticastDelegate(Multi.Add);  
  29.             del1 += new MulticastDelegate(Multi.Multiply);  
  30.             Console.WriteLine("calling add() and multiply() methods.\n");  
  31.             del1(6, 5);  
  32.   
  33.             del1 -= new MulticastDelegate(Multi.Add);  
  34.             Console.WriteLine("add() method unsubcribed.\n");  
  35.             del1(7, 5);  
  36.         }  
  37.     }  
  38. }  
Output
 
Delegates In C#
 
In the above code, the delegate named MultiCast delegate is subscribing to the Multiply method using the += operator. Later in the code, we have unsubscribed the add() method here and then we are calling the delegate object del1 once again and passing in the two integer values. Now it will just subscribe to Multiply() method and then call that method.
 

Summary

 
In this article, we have demonstrated how to define a delegate and then with the help of a proper code snippet, we have demonstrated how to use delegate objects to call different methods. We have also shown how to use a single delegate to subscribe to more than one method using the concept of Multicasting.