Walkthrough

Delegates is a word that horrifies new programmers but here I am trying to make it as simple as I can. After reading this article you will find that Delegates are easy to use and learn.

Delegates in C# is a great feature in the language, since we previously had pointers those were unsafe and are not typesafe but here in C# Delegates are both safe and typesafe both.

Delegates as a real meaning in English is “Entrust” a task or responsibility given to another person, typically one who is less senior than oneself, we can say that Delegates are the representative, for example, Indian delegates for US are the representative of India in US delegate works as a bridge between the two countries.

There are four steps to use a delegate in C#.

Step 1: Declare a Delegate.

Step 2: Define the handler Method.

Step 3: Instantiate the delegate.

Step 4: Use Delegate.

The following is an example program for Delegate.

  1. using System;
  2. namespace Sumit_Delegate_Sample
  3. {
  4. class Program
  5. {
  6. // STEP 1: Declare a Delegate
  7. public delegate int DoAll(int a, int b);
  8. static void Main(string[] args)
  9. {
  10. // Create instance of delegate
  11. DoAll doit = add;
  12. // Use Delegate like a method
  13. Console.WriteLine("Output is: "+ doit(2,3));
  14. Console.ReadKey();
  15. }
  16. // STEP 2: Define handeler Method (Declare a method with the same signature as the delegate.)
  17. public static int add(int x, int y)
  18. {
  19. return x+y;
  20. }
  21. }
  22. }
Above example is an example for Single-cast Delegate in which only one method is assigned to the delegate.

The Output of program is:

Output

Thanks Folks!