Dot Net For All

C# Delegate with example

C# delegate Introduction

In this article I will discuss about the basics of delegate in C# and how CLR behaves with them explained with a code example. Delegates are reference types that take a method as parameter and once the delegate is invoked the method is called. Once we declare a delegate we need to provide the parameters that the referenced function is expecting and also provide the return type of that function as shown below.

public delegate void MyDelegate(int number);

The preceding delegate expects a method that takes a single integer parameter and returns void.

C# Delegates Explained

Suppose we declare a C# delegate as shown in the code listing below:

public class DelegareUsage  
{  
   public delegate void MyDelegate(int number);  
}

What the CLR does is it creates a class in the IL code as shown in the figure below.

C# delegate

As we can see in the above figure a sealed class is created in the IL after the compilation of the code. As we can see the delegate class contains three functions i.e. BeginInvoke, EndInvoke, Invoke.

How a C# Delegate is Initialized

We can create an instance of the delegate as shown below

MyDelegate del = new MyDelegate(Display);

Or alternatively we can also initialize a delegate as follows by directly assigning the method to the delegate instance.

MyDelegate del = Display;

In both of the preceding cases a variable of type MyDelegate is created that would be further used to call the method synchronously or asynchronously.

Now why did I say synchronously or asynchronously? As described earlier, every time a delegate is declared, two types of methods are created that can be used to call the referenced method. They are:

1. Invoke: This is the default way by which a method is being called. Suppose I have a method as shown below:

public static void Display(int display) {
Console.WriteLine(display);
}

And I want to call this method synchronously I can do it in the following ways

del.Invoke(10); or
del(10);

2. BeginInvoke: Now suppose I have a function that takes time to execute and I want to return as soon as the function is called. This I can do as in the following.

del.BeginInvoke(10,null, null)  
public static void TimeTakingFunction(int display)  
{  
   Thread.Sleep(5000);  
   Console.WriteLine(display);  
}

This will return control to the caller as soon as the preceding statement is executed and it will not wait for the function to return or end the execution.

MultiCast Delegate

The hierarchy of the inheritance for the delegates is that the user defined delegate is derived from a multicast delegate. Each delegate contains an invocation list, in other words we can attach any number of functions to the delegates. The functions can be attached to the invocation list using the operator +=. The functions in the multicast delegates are called in the order they are added. We usually expect a multicast delegate to return void as if we have multiple functions that return anything but void in that case the value returned from the last called function is retained in the variable.

class Program  
{  
   public delegate void MyDelegate(int number);  
   static void Main(string[] args)  
   {  
      MyDelegate del = TimeTakingFunction;  
      del += AnotherTimeTakinFunction;  
      del.Invoke(10);  
      Console.WriteLine("In the main");  
      Console.ReadKey();  
   }  
   public static void Display(int display)  
   {  
      Console.WriteLine(display);  
      Console.ReadKey();  
   }  
   public static void TimeTakingFunction(int display)  
   {  
      Thread.Sleep(5000);  
      Console.WriteLine("First time taking function " + display);  
   }  
   public static void AnotherTimeTakinFunction(int display)  
   {  
      Thread.Sleep(5000);  
      Console.WriteLine("Second time taking function " + display);  
   }  
}

Going further you can learn about the Func Action, predicate and anonymous methods.  This was all about the basics of delegates. Please provide your comments about the article.

Further Reading:

  1. Anonymous Methods and Lambda Expression
  2. Action Func and predicate
  3. Observer pattern using delegate

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview