Delgates are similar to a function pointer in C language.

A delegate is an object which stores the reference/address of a function.

A delegate can hold the reference of only those functions whose signature matches with that of a function.

Syntax:

<accessModifier> delegate <datatype> <nameofdelegate>(<arg1>,<arg2>)

There are 2 types of delegates:

  1. Unicast delegate
  2. Multicast delegate

1. Unicast delegate holds the reference of one function.

Example:

  1. using System;
  2. namespace unicast
  3. {
  4. public delegate int AddDelegate(int x, int y);
  5. class program
  6. {
  7. static void Main()
  8. {
  9. AddDelegate dlg = new AddDelegate(Add);
  10. int r = dlg.Invoke(10, 20);
  11. Console.WriteLine("Sum is {0}", r);
  12. Console.ReadKey();
  13. }
  14. public static int Add(int x, int y)
  15. {
  16. return (x + y);
  17. }
  18. }
  19. }
Output:

Sum is 30


2.

  • Multicast delegate multicast delegate holds the reference of more than one function.
  • Return type should be void.

Example:

  1. using System;
  2. namespace multicast
  3. {
  4. public delegate void AddDelegate(int x, int y);
  5. class program
  6. {
  7. static void Main()
  8. {
  9. AddDelegate dlg = new AddDelegate(Add);
  10. dlg = dlg + new AddDelegate(Substract);
  11. dlg.Invoke(10, 20);
  12. Console.ReadKey();
  13. }
  14. public static void Add(int x, int y)
  15. {
  16. Console.WriteLine ("Sum is {0}",(x+ y));
  17. }
  18. public static void Substract(int x, int y)
  19. {
  20. Console.WriteLine("Difference is {0}", (x - y));
  21. }
  22. }
  23. }
Output:

Sum is 30
Difference is -10