Delegates

C# Contains two kinds of objects, those that create changes and those that respond to that changes. A Delegates acts as a tunnel between these two kinds of objects that move information from one side to another.

A C# delegates are class methods and can be either static or instance class methods. A delegate can keep track of its own state by maintain information in the object to which it belongs.

We can create delegates by using “Delegate” Keyword as shown below:

  1. Public delegate int MyDelegate (int x);
A Delegate is not a method or a function it’s a kind of definition of function pointer. Therefore you cannot directly use a Delegate you need a function associated with it.

For creating a delegate use these two steps:
  1. You need to have a delegate in a class that acts the conduit pointer for use by the delegate source.

  2. You need a live method that acts as the concrete functionality that is called when delegate is invoked.

Let’s Create one simple Program of delegates in Console:

Program of delegates in Console

Here is the Code of Delegates:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Delegates_demo
  6. {
  7. public delegate int Mydelegate(int x,int y);
  8. class sample
  9. {
  10. public static int rectangle(int a, int b)
  11. {
  12. return a * b;
  13. }
  14. }
  15. class Program
  16. {
  17. static void Main(string[] args)
  18. {
  19. Console.WriteLine("My simple Delegate Program");
  20. Mydelegate mdl = new Mydelegate(sample.rectangle);
  21. Console.WriteLine("The Area of rectangle is {0}", mdl(4, 5));
  22. Console.ReadKey();
  23. }
  24. }
  25. }
Output of Delegates:

Output of Delegates

Hope you like this Article. Have a good day! Thank you for Reading!