In this article, we will learn Delegate in C#.NET with example, Type of delegate in c# [real time] example and Anonymous method. I will explain Singlecast Delegate and Multicast Delegate in c#.net with an example [step by step].
What is the Delegate?
It is type safe function pointer. Which hold the reference/address of the method.
Type safe function means
1. The return type of delegate should be the same as the return type of method.
2. The parameter type of delegate should be the same as the parameter type of method.
In order to work with the delegate, we have to follow three steps as follow.
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 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 instantiating 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 the 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 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("shrimantvt@gmail.com");
- 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.
- email("shrimantvt@gmail.com");
- message();
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("shrimantvt@gmail.com");
- Console.WriteLine(strEmail);
- message.Invoke();
- Console.ReadLine();
- }
- }
- }
Output:
Type of delegate in c#
- Singlecast Delegate
- Multicast Delegate
Whenever the delegate instance refers to 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 is points to only one method like 'CalculateArea'.so that type of delegate is said to be singlecast delegate.
Output:
Whenever the delegate instance is points/refers to address of more than one method. then these type of delegate is said to be the multicast delegate.
There are two way 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 class name like "Rectangle" having two methods like CalculateArea and CalculatePerimeter of the rectangle as follow.
- 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 the above example, there are one delegate instance points to the more than one methods.
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 method without having name. we can use anonymous method in delegates.it is used to write less code. It has high performance as compare to normal delegate.
Advantages:
- Write less code
- High performance
Example 1: This is the simple example to understand the concepts of the anonymous method.
we can take the above same example with having 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 on below example there is no any method declaration. we have directly define 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.