C# Delegate Tutorial – How To Instantiate And Work With Delegates

This Tutorial Explains How To Use A C# Delegate With The Help Of Simple Code Examples. You Will Also Learn About Multicast Delegates in C#:

What Are C# Delegates?

In C#, delegates are similar to pointers available in C++. It is basically a reference type variable that contains a reference to another method.

Further, its reference cannot be changed during the run time. It is available inside System.Delegate class. A delegate is used to handle call back function or an event handler.

It is like a pointer to a function and can be declared using the keyword delegate followed by the signature of the function.

=> Read Through The Entire C# Training Series Here

C# Delegate

The declaration of the delegate also determines the method that can be referred by the delegate i.e. it can be a reference method that has the same signature as a delegate.

Instantiating Delegate In C#

Once the delegate is declared, it can be instantiated with the new keyword and then it needs to be associated with the method. Just like a method, the expression needs to pass an argument.

Invoking A Delegate

A delegate can be invoked just like a method.

Example:

class Program
       {
public delegate void methodDelegate();
public static void Main(string[] args)
                {
            
methodDelegate md = new methodDelegate(method);
md.Invoke();
        
                  }
        
public static void method()
                 {
Console.WriteLine("Delegate pointing to method"); 
                 }
          }

Output

The output of the above program will be:

Delegate pointing to method

Explanation

In the above program, we have created an object of the delegate and pointed it towards the method that we need to invoke. Then we used the invoke() to invoke the method using ‘delegate'.

Why Do We Need To Use C# Delegate?

We could have called the method directly from our main method but why do we really need to use a delegate?

Delegate in simple language means a representative for communication between two groups. Even in a programming context, it has a similar role. It is used for Callbacks.

Let's assume that we have a long-running method and we need to check that run progress continuously. To do that we use callback using a delegate. This allows us to keep track of the long-running method.

For Example:

public class Program
       { 
               One on = new One();
        
public static void Main(string[] args)
                {
One.generateNumbers(callDelegate);
Console.ReadLine();
                 }

public static void callDelegate(int j)
                {
Console.WriteLine("The current random number is :" + j);
                }

      
        }
public class One { 

public delegate void callingDelegate(int j);

public static void generateNumbers(callingDelegate cd)
              {
                        Random rn = new Random();
 int i = 0;
int j = 0;
while (i < 10)
                       {
                                  j = rn.Next(9999);
                                 cd(j);
i++;
                       }
                }
       }

The output of the above program will be:

Output

The current random number is :1559
The current random number is :6127
The current random number is :6639
The current random number is :3963
The current random number is :4479
The current random number is :6898
The current random number is :1390
The current random number is :6409
The current random number is :2629
The current random number is :5464

In the above program, we used a delegate to get a callback from the “generateNumber” method that generates a random integer for a given iteration. This iteration can be huge. Hence, the delegate here is used to get a call back every time when a random integer is generated in the method.

What Is A Multicast Delegate In C#?

A delegate can point to several different methods. A delegate that points to several different methods is known as a multicast delegate. A “+” sign (operator) is used to add a function to the delegate and the “-“ sign (operator) is used to remove any existing function attached to the delegate.

A multicast delegate calls the functions it is pointed to and only the same type of functions can be combined to form a multi-cast delegate. This can be used to create a list of methods that need to be invoked by calling a single delegate.

Let's have a look at a simple program to understand this:

Program

public class Program
        {
delegate void IntegerCounter(int n);

public static void method_A(int a)
               {
                     a = a + 5;
Console.WriteLine("the value of first method  {0}", a);
                }

        
public static void method_B(int b)
               {
                      b = b * 5;
Console.WriteLine("the value of second method  {0}", b);

                }


public static void Main(string[] args)
               {
//creating instance of the delegate

IntegerCounter x;
IntegerCounter y = new IntegerCounter(method_A);
IntegerCounter z = new IntegerCounter(method_B);
                        x = y;
                        x += z;

x(10);

Console.ReadLine();
                 }
        
          }

Output

the value of first method 5
the value of second method 50

In the above program, we declared a delegate IntegerCounter. Then we created two different methods that are performing a certain operation on the integer value. Then in the main method, we initialized delegate for both the defined methods.

Then we first used the delegate object to point to the first initialized delegate method and after that, we used the “+” sign to multicast delegate and point to another method. Then if we pass an integer parameter both methods will be receiving the same parameter and will be executed.

Conclusion

A delegate is a pointer to a function. The method that is going to use the delegate must have the same parameter and return type.

The delegate can be declared similar to a function and can also be invoked similarly. A multicast delegate is when we use the delegate to point to multiple methods and a plus “+” operator is used to use multicast.

=> Explore The Entire Series Of C# Training Tutorials Here