Delegate In C# In A Simple Way

In this post, we will discuss Delegate in C#.NET, Type of delegate and Anonymous method. I will explain Delegate in detail with an example in a simple way.

What is the Delegate?

It is type safe function pointer which holds the reference/address of the method.

Type safe function means:

  1. The return type of delegate should be same as the return type of method.
  2. The parameter type of delegate should be the same as parameter type of method.
In order to work with the delegate, we have to follow three steps as follows.

Step 1

Define a Delegate.

  1. [<modifier>] delegate void|type(return_type) <delegate_name>([<parameter list>]);  
e.g
  1. public delegate void MessageDelegate();  

Step 2

Instantiating the delegate or binding method to the delegate instance.

  1. <delegate_name> object_name = new <delegate_name>(<method_name>);  

OR

  1. <delegate_name> object_name = <method_name>;  
e.g
  1. // Step-2: Instantiating the Delegate.  
  2. MessageDelegate message = new MessageDelegate(Email.DisplayMessage);  

Note
<method_name> If the method is static then, we call it by using the class name. If the method is non-static then we can call that method by using object of the class.

There is two way to instantiate the delegate as mentioned above. I will go through one by one in the example so that you can understand better.

Step 3

Invoking the delegate.

  1. <delegate_object>.Invoke(<parameters>);  

OR

  1. <delegate_object>(<parameters>);  
e.g
  1. // Step-3: Invoking the delegate  
  2. message.Invoke();  
Note
<parameters> We can pass parameters as we mentioned to the respective methods.

Example 1

This is a very simple example to understand the basic concepts of the delegate.

Step 1 - Define a delegate

Note

We can define the delegate inside the namespace or class.
  1. // Step-1: Define a Delegate  
  2. public delegate void MessageDelegate();  
  3. public delegate string EmailDelegate(string strEmail);  

Create class having names like "Email" and two methods as follow.

  1. public class Email {  
  2.     public static string GetEmail(string strEmail) {  
  3.         return "Your Email Id is " + strEmail;  
  4.     }  
  5.     public static void DisplayMessage() {  
  6.         Console.WriteLine("Welcome to CSharp Corner");  
  7.     }  
  8. }  

Step 2

Instantiating the delegate

  1. // Step-2: Instantiating the Delegate.  
  2. EmailDelegate email = new EmailDelegate(Email.GetEmail);  
  3. MessageDelegate message = new MessageDelegate(Email.DisplayMessage);  

The second way to do the binding method to the delegate instance:

  1. //OR  
  2. // Step-2: Binding method to the Delegate instance.  
  3. EmailDelegate email = Email.GetEmail;  
  4. MessageDelegate message = Email.DisplayMessage;  

Step 3

Invoking the delegate or binding method to delegate instance.

  1. // Step-3: Invoking the delegate  
  2. string strEmail= email.Invoke("[email protected]");  
  3. Console.WriteLine(strEmail);  
  4. message.Invoke();  

We can invoke method by using "Invoke()" method or we can pass direct parameter to the delegate instance as following.

  1. // Step-3: Invoking the delegate second way  
  2. email("[email protected]");  
  3. message();  

Program Code

  1. using System;  
  2. namespace DelegateDemo {  
  3.     // Step-1: Define a Delegate  
  4.     public delegate void MessageDelegate();  
  5.     public delegate string EmailDelegate(string strEmail);  
  6.     public class Email {  
  7.         public static string GetEmail(string strEmail) {  
  8.             return "Your Email Id is " + strEmail;  
  9.         }  
  10.         public static void DisplayMessage() {  
  11.             Console.WriteLine("Welcome to CSharp Corner");  
  12.         }  
  13.     }  
  14.     class Program {  
  15.         static void Main(string[] args) {  
  16.             // Step-2: Instantiating the Delegate.  
  17.             EmailDelegate email = new EmailDelegate(Email.GetEmail);  
  18.             MessageDelegate message = new MessageDelegate(Email.DisplayMessage);  
  19.             // Step-3: Invoking the delegate  
  20.             string strEmail = email.Invoke("[email protected]");  
  21.             Console.WriteLine(strEmail);  
  22.             message.Invoke();  
  23.             Console.ReadLine();  
  24.         }  
  25.     }  
  26. }  
Output


Type of delegate in c#
  • Singlecast Delegate
  • Multicast Delegate
Singlecast Delegates
Whenever the delegate instance refers to the address of the single method, then it is said to be single cast delegate.

Example 2

This is a simple example to understand the basic concept of 'single cast delegate'.

Program Code
  1. using System;  
  2. namespace DelegateDemo {  
  3.     // Step-1: Define a delegate  
  4.     public delegate double AreaDelegate(double width, double height);  
  5.     public class Rectangle {  
  6.         public static double CalculateArea(double width, double height) {  
  7.             return (width * height);  
  8.         }  
  9.     }  
  10.     class DelegateExampleTwo {  
  11.         static void Main(string[] args) {  
  12.             //Step-2: Instantiating the delegate  
  13.             AreaDelegate area = new AreaDelegate(Rectangle.CalculateArea);  
  14.             // OR  
  15.             //Step-3: Binding method to delegate instance  
  16.             AreaDelegate area1 = Rectangle.CalculateArea;  
  17.             // Step-3: Invoking the Delegate by using invoke method  
  18.             Console.WriteLine("Using invoke method");  
  19.             Console.WriteLine("Area of Rectangle is {0}", area.Invoke(10.10, 20.10));  
  20.             // OR  
  21.             Console.WriteLine("-------------------------------------------------");  
  22.             // Step-3: Invoking the Delegate without using the invoke method  
  23.             Console.WriteLine("Without using invoke method");  
  24.             Console.WriteLine("Area of Rectangle is {0} ", area1(10.10, 20.10));  
  25.             Console.ReadLine();  
  26.         }  
  27.     }  
  28. }  
Note
In the above example the delegate instance points to only one method like 'CalculateArea', so that type of delegate is said to be singlecast delegate.

Output


 

Multicast Delegate
Whenever the delegate instance points/refers to an address of more than one method, then these types of delegates are said to be multicast delegates.

There are two ways of calling the multiple methods
  • "+="
  • "+"
Step 1

Define a delegate.

Note
We can define the delegate inside the namespace or class.
  1. // Step-1: Define a delegate  
  2. public delegate double RectangleDelegate(double width,double height);  
Create a class name like "Rectangle" having two methods, like CalculateArea and CalculatePerimeter of the rectangle as follows,
  1. public class Rectangle {  
  2.     public static double CalculateArea(double width, double height) {  
  3.         return (width * height);  
  4.     }  
  5.     public static double CalculatePerimeter(double width, double height) {  
  6.         return 2 * (width + height);  
  7.     }  
  8. }  
Step 2

Instantiating the delegate.
  1. //Step-2: Instantiating the delegate  
  2. RectangleDelegate rectangle = Rectangle.CalculateArea;  
  3. rectangle += Rectangle.CalculatePerimeter;  
Note

You can see in the above example, there is one delegate instance which points to more than one method.

Step 3

Invoking the delegate.
  1. // Step-3: Invoking the Delegate by using invoke method  
  2. Console.WriteLine("Area of Rectangle is {0}", rectangle.Invoke(10.10, 20.10));  
  3. Console.WriteLine("Perimeter of Rectangle is {0}", rectangle.Invoke(11.10, 21.22));  
Program Code
  1. using System;  
  2. namespace DelegateDemo {  
  3.     // Step-1: Define a delegate  
  4.     public delegate double RectangleDelegate(double width, double height);  
  5.     public class Rectangle {  
  6.         public static double CalculateArea(double width, double height) {  
  7.             return (width * height);  
  8.         }  
  9.         public static double CalculatePerimeter(double width, double height) {  
  10.             return 2 * (width + height);  
  11.         }  
  12.     }  
  13.     class DelegateExampleTwo {  
  14.         static void Main(string[] args) {  
  15.             //Step-2: Instantiating the delegate  
  16.             RectangleDelegate rectangle = Rectangle.CalculateArea;  
  17.             rectangle += Rectangle.CalculatePerimeter;  
  18.             //Step-3: Invoking the Delegate by using invoke method  
  19.             Console.WriteLine("Area of Rectangle is {0}", rectangle.Invoke(10.10, 20.10));  
  20.             Console.WriteLine("Perimeter of Rectangle is {0}", rectangle.Invoke(11.10, 21.22));  
  21.             Console.ReadLine();  
  22.         }  
  23.     }  
  24. }  
Output

Anonymous Method

You can simply say, it is a method without a name. We can use anonymous method in delegates. It is used to write less code. It has high performance as compared to normal delegate.

Advantages
  • Write less code
  • High performance
Example 1

This is a simple example to understand the concepts of the anonymous method. We can take the above same example with only one method, 'CalculateArea'

Step 1

Define a delegate
  1. // Step-1: Define a delegate  
  2. public delegate double RectangleDelegate(double width, double height);  
Step 2

Instantiating the delegate

Note

We can see in the below example there is not any method declaration. We have directly defined method body to the delegate.
  1. //Step-2: Instantiating the delegate by using anonymous method  
  2. RectangleDelegate rectangle = delegate(double width, double height)  
  3. {  
  4.    return (width * height);  
  5. };  
Step 3

Invoking the delegate
  1. // Step-3: Invoking the Delegate  
  2. onsole.WriteLine("Area of Rectangle is {0}", rectangle.Invoke(10.10, 20.10));  
Program code
  1. using System;  
  2. namespace DelegateDemo {  
  3.     // Step-1: Define a delegate  
  4.     public delegate double RectangleDelegate(double width, double height);  
  5.     class AnonymousMethod {  
  6.         static void Main(string[] args) {  
  7.             // Step-2: Instantiating the delegate by using anonymous method  
  8.             RectangleDelegate rectangle = delegate(double width, double height) {  
  9.                 return (width * height);  
  10.             };  
  11.             // Step-3: Invoking the Delegate  
  12.             Console.WriteLine("Area of Rectangle is {0}", rectangle.Invoke(10.10, 20.10));  
  13.             Console.ReadLine();  
  14.         }  
  15.     }  
  16. }  
Usages of Delegate
  • It is used in Event
  • It is used in Threading
  • It is used to Callback Function
  • It is used in Multicasting
I hope you understood the basic concept of the delegate, type of delegate and anonymous method. If you like, then add your valuable feedback that will encourage me to write more articles.