What are Delegates?

You can start thinking of a Delegate as an object that holds one or more methods. Normally, you cannot execute an object, but Delegate is a different thing. Of course, you can execute a Delegate and when you do, it executes all the methods that it holds.

In this blog, I’ll explain basic syntax and semantics of creating and using Delegates. Later, you will see how you can use Delegates to pass an executable code from the method to another and its importance.

Note

If you are from a C++ background, then the easiest way to understand Delegates is to think of them as a type safe, object oriented function pointers.

We will start with a short example.

  1. using System;
  2. public delegate void MyDel();
  3. class Program
  4. {
  5. public void Method1()
  6. {
  7. Console.WriteLine("Method1..");
  8. }
  9. public void Method2()
  10. {
  11. Console.WriteLine("Method2..");
  12. }
  13. public void Method3()
  14. {
  15. Console.WriteLine("Method3..");
  16. }
  17. public void Method4()
  18. {
  19. Console.WriteLine("Method4..");
  20. }
  21. static void Main(string[] args)
  22. {
  23. Program p = new Program();
  24. MyDel del = new MyDel(p.Method1);
  25. del += p.Method2;
  26. MyDel del1 = new MyDel(p.Method3);
  27. del1 += p.Method4;
  28. del();
  29. del1();
  30. Console.ReadLine();
  31. }
  32. }

Overview of Delegate

A Delegate is user-defined and reference type is just a class but the class specifies the collection of the data, methods and delegate contains a list of methods executes at the runtime.

You will need five steps to create a Delegate.

  1. Declare a Delegate type it looks like a methods signature.
  2. Declare a Delegate variable of a Delegate type.
  3. Creates an object of a Delegate type and assign it to the Delegate variable.
  4. Add the methods into Delegate object (methods must have same signature and return type as the Delegate type defined in the first step).
  5. You can invoke your Delegate throughout your code. When you do each method in the Delegate, the list will be fired

Delegate is a reference to call the multiple methods at a time. They are also known as function pointers.

Delegate contains an ordered list of the methods of the same signature and the return type.

Declare the Delegate Type

A Delegate type must be declared before you can use it to create the variables and the objects of the Delegate type.

Keyword Delegate type name

delegate void MyDel(int x)

Return type

Delegate type declaration is different from the method declaration in two ways. Delegate starts with a keyword Delegate and does not have any method body. It does not need to declare inside a class because it is a type declaration.

Creating Delegate Objects

As Delegate is a reference type, so it has both a reference and an object. After declaring a type, you can declare the variable and create the objects.

Delegate type name

MyDel del

Variable

There are two ways to declare Delegates objects.

  1. del = new MyDel(p.Method1);

Instance method

There is an implicit conversion between the method name and a Delegate type, so you can also use it.

  1. del = p.Method1;


Adding methods to Delegates

You can add the methods to Delegate by using += operator. For example, the code given below adds four methods in the invocation list of Delegate.

  1. MyDel del = p.Method1;
  2. += p.Method2;
  3. += p.Method3;
  4. += p.Method4;

Removing methods from Delegates

You can remove a method from Delegate by using -= operator. For example, the code given below removes two methods from the invocation list of Delegate.

  1. MyDel del = p.Method1;
  2. += p.Method2;
  3. -= p.Method3;
  4. -= p.Method4;


Attempting to invoke an empty Delegate throws an exception. If Delegate list is empty, Delegate will be null.

Example

In the code given below, we have a Delegate type MyDel with an integer parameter and three classes are named Physics and Mathematics, and Program. Class Mathematics contains three methods. Class Physics also contains three methods.

  1. using System;
  2. public delegate void MyDelegate(int a);
  3. class Mathematics
  4. {
  5. public void MathMethod1(int x)
  6. {
  7. Console.WriteLine("MathMethod1: returning:{0}",x+1);
  8. }
  9. public void MathMethod3(int x)
  10. {
  11. Console.WriteLine("MathMethod3: returning:{0}", x + 3);
  12. }
  13. public int MathMethod4(int x, int y)
  14. {
  15. return x + y;
  16. }
  17. }
  18. class Physics
  19. {
  20. public void PhysicsMethod1(int x)
  21. {
  22. Console.WriteLine("PhysicsMethod1: returning:{0}", x + 7);
  23. }
  24. public int PhysicsMethod3(int x, int y , int z)
  25. {
  26. return x + y + z;
  27. }
  28. public void PhysicsMethod2(int x)
  29. {
  30. Console.WriteLine("PhysicsMethod2: returning:{0}", x + 10);
  31. }
  32. }
  33. class Program
  34. {
  35. static void Main(string[] args)
  36. {
  37. Mathematics m = new Mathematics();
  38. Physics p = new Physics();
  39. MyDelegate md = new MyDelegate(m.MathMethod1);
  40. md += m.MathMethod2;
  41. md += m.MathMethod3;
  42. md += p.PhysicsMethod1;
  43. md += p.PhysicsMethod2;
  44. md += p.PhysicsMethod3;
  45. md(2);
  46. Console.ReadLine();
  47. }
  48. }

This code will produce the compile time error, which is shown below.




Note that Physics class contains a method with the two integer parameters and Mathematics class also contains a method with the three integer parameters, which are different from Delegate type declared in the first step. It must to have same signature and return type of methods as your Delegate type. Remove these two methods, begin the execution and you will get the output, as shown below.