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:
- The return type of delegate should be same as the return type of method.
- 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.
- [<modifier>] delegate void|type(return_type) <delegate_name>([<parameter list>]);
e.g
- public delegate void MessageDelegate();
Step 2
Instantiating the delegate or binding method to the delegate instance.
- <delegate_name> object_name = new <delegate_name>(<method_name>);
OR
- <delegate_name> object_name = <method_name>;
e.g
-
- 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.
- <delegate_object>.Invoke(<parameters>);
OR
- <delegate_object>(<parameters>);
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.
-
- public delegate void MessageDelegate();
- public delegate string EmailDelegate(string strEmail);
Create class having names like "Email" and two methods as follow.
- public class Email {
- public static string GetEmail(string strEmail) {
- return "Your Email Id is " + strEmail;
- }
- public static void DisplayMessage() {
- Console.WriteLine("Welcome to CSharp Corner");
- }
- }
Step 2
Instantiating the delegate
-
- EmailDelegate email = new EmailDelegate(Email.GetEmail);
- MessageDelegate message = new MessageDelegate(Email.DisplayMessage);
The second way to do the binding method to the delegate instance:
-
-
- EmailDelegate email = Email.GetEmail;
- MessageDelegate message = Email.DisplayMessage;
Step 3
Invoking the delegate or binding method to delegate instance.
-
- string strEmail= email.Invoke("[email protected]");
- Console.WriteLine(strEmail);
- message.Invoke();
We can invoke method by using "Invoke()" method or we can pass direct parameter to the delegate instance as following.
Program Code
- using System;
- namespace DelegateDemo {
-
- public delegate void MessageDelegate();
- public delegate string EmailDelegate(string strEmail);
- public class Email {
- public static string GetEmail(string strEmail) {
- return "Your Email Id is " + strEmail;
- }
- public static void DisplayMessage() {
- Console.WriteLine("Welcome to CSharp Corner");
- }
- }
- class Program {
- static void Main(string[] args) {
-
- EmailDelegate email = new EmailDelegate(Email.GetEmail);
- MessageDelegate message = new MessageDelegate(Email.DisplayMessage);
-
- string strEmail = email.Invoke("[email protected]");
- Console.WriteLine(strEmail);
- message.Invoke();
- Console.ReadLine();
- }
- }
- }
Output
Type of delegate in c#
- Singlecast Delegate
- Multicast Delegate
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
- using System;
- namespace DelegateDemo {
-
- public delegate double AreaDelegate(double width, double height);
- public class Rectangle {
- public static double CalculateArea(double width, double height) {
- return (width * height);
- }
- }
- class DelegateExampleTwo {
- static void Main(string[] args) {
-
- AreaDelegate area = new AreaDelegate(Rectangle.CalculateArea);
-
-
- AreaDelegate area1 = Rectangle.CalculateArea;
-
- Console.WriteLine("Using invoke method");
- Console.WriteLine("Area of Rectangle is {0}", area.Invoke(10.10, 20.10));
-
- Console.WriteLine("-------------------------------------------------");
-
- Console.WriteLine("Without using invoke method");
- Console.WriteLine("Area of Rectangle is {0} ", area1(10.10, 20.10));
- Console.ReadLine();
- }
- }
- }
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.
-
- 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,
- public class Rectangle {
- public static double CalculateArea(double width, double height) {
- return (width * height);
- }
- public static double CalculatePerimeter(double width, double height) {
- return 2 * (width + height);
- }
- }
Step 2
Instantiating the delegate.
-
- RectangleDelegate rectangle = Rectangle.CalculateArea;
- 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.
-
- Console.WriteLine("Area of Rectangle is {0}", rectangle.Invoke(10.10, 20.10));
- Console.WriteLine("Perimeter of Rectangle is {0}", rectangle.Invoke(11.10, 21.22));
Program Code
- using System;
- namespace DelegateDemo {
-
- public delegate double RectangleDelegate(double width, double height);
- public class Rectangle {
- public static double CalculateArea(double width, double height) {
- return (width * height);
- }
- public static double CalculatePerimeter(double width, double height) {
- return 2 * (width + height);
- }
- }
- class DelegateExampleTwo {
- static void Main(string[] args) {
-
- RectangleDelegate rectangle = Rectangle.CalculateArea;
- rectangle += Rectangle.CalculatePerimeter;
-
- Console.WriteLine("Area of Rectangle is {0}", rectangle.Invoke(10.10, 20.10));
- Console.WriteLine("Perimeter of Rectangle is {0}", rectangle.Invoke(11.10, 21.22));
- Console.ReadLine();
- }
- }
- }
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
-
- 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.
-
- RectangleDelegate rectangle = delegate(double width, double height)
- {
- return (width * height);
- };
Step 3
Invoking the delegate
-
- onsole.WriteLine("Area of Rectangle is {0}", rectangle.Invoke(10.10, 20.10));
Program code
- using System;
- namespace DelegateDemo {
-
- public delegate double RectangleDelegate(double width, double height);
- class AnonymousMethod {
- static void Main(string[] args) {
-
- RectangleDelegate rectangle = delegate(double width, double height) {
- return (width * height);
- };
-
- Console.WriteLine("Area of Rectangle is {0}", rectangle.Invoke(10.10, 20.10));
- Console.ReadLine();
- }
- }
- }
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.