Delegates In C#

Dictionary meaning

    A person sent or authorized to represent others “or “A person designated to act for or represent another or others"

History of Delegate in C#

The diagram shows the history of delegates by C# version,

history of delegates

A delegate is a class that can hold a reference (source of information) to a method. We can say that delegate is like a pointer to a function.

Every delegate object is implicitly derived from class Delegate.

Declaration of Delegate

A delegate can be declared using delegate keyword followed by a function signature as shown below:

Signature of a Single Cast Delegate

    <access modifier> delegate <return type> <delegate-name>(< parameter list >)

Example
  1. public delegate void myDelegate(string myMessage);  
Delegate class has four steps process for defining and using delegates – Declaration, Reference, Target and Invoke.

The first step is to declare the delegate with the return type and input parameters.
  1. // Delegates declaration  
  2. public delegate int myDelegate(int a, int b);  
  3. Which is having same signature as method below.  
  4. public int Sum(int a, int b)  
  5. {  
  6.    return a + b;  
  7. }  
The second step is to create a delegate reference.
  1. // Create delegate reference  
  2. DelegateClass.myDelegate objSum = null;  
The third step is to target/point the delegate reference to an object instance.
  1. // Target the reference to the Sum method  
  2. objSum = objMyclass.Sum;  
The final step is to invoke the delegate like invoking a regular method.
  1. // Invoke the delegate  
  2. Console.WriteLine("Sum of two integer is = " + objSum(10, 20));  
  3. Console.ReadLine();  
Finally the Sample Code
  1. namespace DelegatesProperties   
  2. {  
  3.     class DelegateClass   
  4.     {  
  5.         // Delegates declaration  
  6.         public delegate int myDelegate(int a, int b);  
  7.   
  8.         // Methods to Target & called by delegate  
  9.         public int Sum(int a, int b)   
  10.         {  
  11.             return a + b;  
  12.         }  
  13.     }  
  14.   
  15.     class Program   
  16.     {  
  17.   
  18.         static void Main(string[] args)   
  19.         {  
  20.             DelegateClass objMyclass = new DelegateClass();  
  21.   
  22.             // Create delegate reference  
  23.             DelegateClass.myDelegate objSum = null;  
  24.   
  25.             // Target/Point the reference to the Sum method  
  26.             objSum = objMyclass.Sum;  
  27.   
  28.             // Invoke the delegate  
  29.             if (objSum != null)   
  30.             {  
  31.                 Console.WriteLine("Sum of two integer is = " + objSum(10, 20));  
  32.                 Console.ReadLine();  
  33.             }  
  34.         }  
  35.     }  
  36. }  
Output

    Sum of two integer is 30;

Let’s do it with Anonymous Method:

  1. namespace DelegateAnonymous  
  2. {  
  3.     class DelegateClass  
  4.     {  
  5.         // Delegates declaration  
  6.         public delegate int myDelegate(int a, int b);  
  7.     }  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             DelegateClass objMyclass = new DelegateClass();  
  13.   
  14.             // Create delegate reference  
  15.             DelegateClass.myDelegate objSum = null;  
  16.   
  17.             // Point the reference to the Sum method  
  18.             objSum = delegate (int a, int b) // Anonymous Method  
  19.             {  
  20.                 return a + b;  
  21.             };  
  22.   
  23.             // Invoke the delegate  
  24.             //objSum.Invoke(20, 10);  
  25.   
  26.             if (objSum != null)  
  27.             {  
  28.                 Console.WriteLine("Sum of two integer is = " + objSum(10, 20));  
  29.                 Console.ReadLine();  
  30.             }  
  31.         }  
  32.     }  
  33. }  
Output 

    Sum of two integer is 30;

Output will be the same as before, this time we have made a little bit change to point the method. Here we use an anonymous method. Let’s take a look how:

  1. objSum = delegate (int a, int b) // Anonymous Method  
  2. {  
  3.    return a + b;  
  4. };  
And the Sum method no more exist in the DelegateClass.
  1. public int Sum(int a, int b)  
  2. {  
  3.    return a + b;  
  4. }  
Types of delegates 
  1. Single cast delegate
  2. Multi cast delegate

Single Cast Delegate

A single cast delegate holds the reference of only single method. This type of delegate is derived from the System.Delegate class.

Note: Our previous example is a single cast delegate

Multi Cast Delegate

The delegate can point to multiple methods. Class MulticastDelegate derives from Delegate and represents a delegate that can invoke more than one method at once.

Internally, MulticastDelegate is implemented as a linked list of delegates.

Add/Remove Delegates

All delegate types declared in C# have implicit operators += and -=. The "+" operator adds a function to the delegate object and the "-" operator removes an existing function from a delegate object.

Sample Example:

  1. namespace MulticastDelegates  
  2. {  
  3.     class DelegateClass  
  4.     {  
  5.         // Delegates declaration  
  6.         public delegate void myDelegate(int a, int b);  
  7.   
  8.         // Methods to Target & called by delegate  
  9.         public void Sum(int a, int b)  
  10.         {  
  11.             Console.WriteLine("Sum of two integer is = " + (a + b));  
  12.         }  
  13.   
  14.         public void Divide(int a, int b)  
  15.         {  
  16.             Console.WriteLine("Divide of two integer is = " + (a / b));  
  17.         }  
  18.   
  19.         public void Multiply(int a, int b)  
  20.         {  
  21.             Console.WriteLine("Multiply of two integer is = " + (a * b));  
  22.         }  
  23.     }  
  24.     class Program  
  25.     {  
  26.         static void Main(string[] args)  
  27.         {  
  28.             DelegateClass objMyclass = new DelegateClass();  
  29.   
  30.             // Create delegate reference  
  31.             DelegateClass.myDelegate objSum = null;  
  32.   
  33.             // Point the reference to the Sum method  
  34.             objSum += objMyclass.Sum;  
  35.             objSum -= objMyclass.Divide;  
  36.             objSum += objMyclass.Multiply;  
  37.   
  38.             // Invoke the delegate  
  39.             if (objSum != null)  
  40.             {  
  41.                 objSum(20, 5);  
  42.                 Console.ReadLine();  
  43.             }  
  44.         }  
  45.     }  
  46. }  
Output 

    Sum of two integer is 25;
    Divide of two integer is 4; not showing this time.
    Multiply of two integer is 100;

Key Notes:

  1. Delegates are reference type.
  2. Delegates are type-safe.
  3. Delegates encapsulates one or more methods.
  4. We can invoke all the methods the delegate is encapsulating with a single call
  5. Delegates allow methods to be passed as parameters.
  6. Invoking a delegate is like as invoking a regular method.
  7. Delegates are used in event handling for defining callback methods.
  8. Once a delegate is created, the method it is associated will never changes because delegates are immutable in nature.
  9. Delegates provide a way to execute methods at run-time.
  10. All delegates are implicitly derived from System.MulticastDelegate, class which is inheriting from System.Delegate class.


Similar Articles