Learn C#.NET, ASP.NET MVC 5,ASP.NET Core that you can increase your knowledge and coding to develop the real-time project.


Friday, May 4, 2018

[C#] - What is Delegates in C# Example | Use of Delegates in C# | Type of Delegates in C#


Delegates in C#

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:
  1. 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:
  1. // Step-2: Instantiating the Delegate.
  2. 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>);
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 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.
  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. {
  3. public static string GetEmail(string strEmail)
  4. {
  5. return "Your Email Id is "+strEmail;
  6. }
  7. public static void DisplayMessage()
  8. {
  9. Console.WriteLine("Welcome to CSharp Corner");
  10. }
  11. }


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 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("shrimantvt@gmail.com");
  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("shrimantvt@gmail.com");
  3. message();

Program Code: 

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


Output:

Delegates in C#

Type of delegate in c#
  • Singlecast Delegate
  • Multicast Delegate
  • Singlecast Delegates:
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:
  1. using System;
  2. namespace DelegateDemo
  3. {
  4. // Step-1: Define a delegate
  5. public delegate double AreaDelegate(double width,double height);
  6. public class Rectangle
  7. {
  8. public static double CalculateArea(double width, double height)
  9. {
  10. return (width*height);
  11. }
  12. }
  13. class DelegateExampleTwo
  14. {
  15. static void Main(string[] args)
  16. {
  17. //Step-2: Instantiating the delegate
  18. AreaDelegate area = new AreaDelegate(Rectangle.CalculateArea);
  19. // OR
  20. //Step-3: Binding method to delegate instance
  21. AreaDelegate area1 = Rectangle.CalculateArea;
  22. // Step-3: Invoking the Delegate by using invoke method
  23. Console.WriteLine("Using invoke method");
  24. Console.WriteLine("Area of Rectangle is {0}", area.Invoke(10.10, 20.10));
  25. // OR
  26. Console.WriteLine("-------------------------------------------------");
  27. // Step-3: Invoking the Delegate without using the invoke method
  28. Console.WriteLine("Without using invoke method");
  29. Console.WriteLine("Area of Rectangle is {0} " , area1(10.10, 20.10));
  30. Console.ReadLine();
  31. }
  32. }
  33. }

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:
Delegates in C#

  • Multicast Delegate:
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.
  1. // Step-1: Define a delegate
  2. 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.
  1. public class Rectangle
  2. {
  3. public static double CalculateArea(double width, double height)
  4. {
  5. return (width*height);
  6. }
  7. public static double CalculatePerimeter(double width, double height)
  8. {
  9. return 2 * (width + height);
  10. }
  11. }

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

Output:
Delegates in C#
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
  1. // Step-1: Define a delegate
  2. 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.
  1. //Step-2: Instantiating the delegate by using the 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. {
  4. // Step-1: Define a delegate
  5. public delegate double RectangleDelegate(double width, double height);
  6. class AnonymousMethod
  7. {
  8. static void Main(string[] args)
  9. {
  10. // Step-2: Instantiating the delegate by using anonymous method
  11. RectangleDelegate rectangle = delegate(double width, double height)
  12. {
  13. return (width * height);
  14. };
  15. // Step-3: Invoking the Delegate
  16. Console.WriteLine("Area of Rectangle is {0}", rectangle.Invoke(10.10, 20.10));
  17. Console.ReadLine();
  18. }
  19. }
  20. }

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.
Share:

3 comments:

Upcoming Articles/Videos

Design Pattern
SOLID Design Principles
Copyright © Programming With Shri | Powered by Shrimant Telgave Home | Disclaimer | Privacy Policy | Terms and Conditions Design by Shrimant Telgave