Delegates In C#

What are Delegates?

You can start thinking of a Delegate as an object that holds one or more methods. Normally, you cannot execute an object, but Delegate is a different thing. Of course, you can execute a Delegate and when you do, it executes all the methods that it holds.

In this blog, I’ll explain basic syntax and semantics of creating and using Delegates. Later, you will see how you can use Delegates to pass an executable code from the method to another and its importance.

Note

If you are from a C++ background, then the easiest way to understand Delegates is to think of them as a type safe, object oriented function pointers.

We will start with a short example.

  • The code starts with a declaration of a delegate type, called MyDel.
  • Class Program has four methods Method1, Method2, Method3, Method4 and Main.
  • In Main, we have two local variables called del and del1, which holds a reference of MyDel to a delegate object.
  • The del contains the list of methods, which includes Method1, Method2 and del1 contains the list of the methods, which includes Method3, and Method4.
  • Finally Main will execute the del and del1 delegate objects, which executes every method held by them. 
  1. using System;  
  2. public delegate void MyDel();  
  3.     class Program  
  4.     {  
  5.  public void Method1()  
  6.         {  
  7.             Console.WriteLine("Method1..");  
  8.         }  
  9.         public void Method2()  
  10.         {  
  11.             Console.WriteLine("Method2..");  
  12.         }  
  13.         public void Method3()  
  14.         {  
  15.             Console.WriteLine("Method3..");  
  16.         }  
  17.         public void Method4()  
  18.         {  
  19.             Console.WriteLine("Method4..");  
  20.         }  
  21.         static void Main(string[] args)  
  22.         {  
  23.             Program p = new Program();  
  24.             MyDel del = new MyDel(p.Method1);  
  25.             del += p.Method2;  
  26.             MyDel del1 = new MyDel(p.Method3);  
  27.             del1 += p.Method4;  
  28.             del();  
  29.             del1();  
  30.             Console.ReadLine();  
  31.         }  
  32.     }   

Overview of Delegate

A Delegate is user-defined and reference type is just a class but the class specifies the collection of the data, methods and delegate contains a list of methods executes at the runtime.

You will need five steps to create a Delegate.

  1. Declare a Delegate type it looks like a methods signature.
  2. Declare a Delegate variable of a Delegate type.
  3. Creates an object of a Delegate type and assign it to the Delegate variable.
  4. Add the methods into Delegate object (methods must have same signature and return type as the Delegate type defined in the first step).
  5. You can invoke your Delegate throughout your code. When you do each method in the Delegate, the list will be fired

Delegate is a reference to call the multiple methods at a time. They are also known as function pointers.

Delegate contains an ordered list of the methods of the same signature and the return type.

  • Methods are held by Delegate and can be from any class or struct.
  • Methods can either be the instance methods or the static methods.

Declare the Delegate Type

A Delegate type must be declared before you can use it to create the variables and the objects of the Delegate type.

Keyword Delegate type name

delegate void MyDel(int x)

Return type

Delegate type declaration is different from the method declaration in two ways. Delegate starts with a keyword Delegate and does not have any method body. It does not need to declare inside a class because it is a type declaration.

Creating Delegate Objects

As Delegate is a reference type, so it has both a reference and an object. After declaring a type, you can declare the variable and create the objects.

Delegate type name

MyDel del

Variable

There are two ways to declare Delegates objects.

 

  1. del = new MyDel(p.Method1);  

 

Instance method

There is an implicit conversion between the method name and a Delegate type, so you can also use it.

 

  1. del = p.Method1;  

 


Adding methods to Delegates

You can add the methods to Delegate by using += operator. For example, the code given below adds four methods in the invocation list of Delegate. 

  1. MyDel del = p.Method1;  
  2.     += p.Method2;  
  3.     += p.Method3;  
  4.     += p.Method4;   

Removing methods from Delegates

You can remove a method from Delegate by using -= operator. For example, the code given below removes two methods from the invocation list of Delegate. 

  1. MyDel del = p.Method1;  
  2.     += p.Method2;  
  3.     -= p.Method3;  
  4.     -= p.Method4;  

 
Attempting to invoke an empty Delegate throws an exception. If Delegate list is empty, Delegate will be null.

Example

In the code given below, we have a Delegate type MyDel with an integer parameter and three classes are named Physics and Mathematics, and Program. Class Mathematics contains three methods. Class Physics also contains three methods. 

  1. using System;  
  2.     public delegate void MyDelegate(int a);  
  3.     class Mathematics  
  4.     {  
  5.         public void MathMethod1(int x)  
  6.         {  
  7.             Console.WriteLine("MathMethod1: returning:{0}",x+1);  
  8.         }  
  9.         public void MathMethod3(int x)  
  10.         {  
  11.             Console.WriteLine("MathMethod3: returning:{0}", x + 3);  
  12.         }  
  13.   
  14.         public int MathMethod4(int x, int y)  
  15.         {  
  16.             return x + y;  
  17.         }  
  18. }  
  19.   
  20. class Physics  
  21.     {  
  22.         public void PhysicsMethod1(int x)  
  23.         {  
  24.             Console.WriteLine("PhysicsMethod1: returning:{0}", x + 7);  
  25.         }  
  26.   
  27.         public int PhysicsMethod3(int x, int y , int z)  
  28.         {  
  29.             return x + y + z;  
  30.         }  
  31.   
  32.         public void PhysicsMethod2(int x)  
  33.         {  
  34.             Console.WriteLine("PhysicsMethod2: returning:{0}", x + 10);  
  35.         }  
  36.     }  
  37.   
  38.     class Program  
  39.     {  
  40.         static void Main(string[] args)  
  41.         {  
  42.             Mathematics m = new Mathematics();  
  43.             Physics p = new Physics();  
  44.   
  45.             MyDelegate md = new MyDelegate(m.MathMethod1);  
  46.             md += m.MathMethod2;  
  47.             md += m.MathMethod3;  
  48.             md += p.PhysicsMethod1;  
  49.             md += p.PhysicsMethod2;  
  50.             md += p.PhysicsMethod3;              
  51. md(2);  
  52.             Console.ReadLine();  
  53.         }  
  54.     }   

This code will produce the compile time error, which is shown below.




Note that Physics class contains a method with the two integer parameters and Mathematics class also contains a method with the three integer parameters, which are different from Delegate type declared in the first step. It must to have same signature and return type of methods as your Delegate type. Remove these two methods, begin the execution and you will get the output, as shown below.