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.
- The code starts with a declaration of a delegate type, called MyDel.
- Class Program has four methods Method1, Method2, Method3, Method4 and Main.
- In Main, we have two local variables called del and del1, which holds a reference of MyDel to a delegate object.
- The del contains the list of methods, which includes Method1, Method2 and del1 contains the list of the methods, which includes Method3, and Method4.
- Finally Main will execute the del and del1 delegate objects, which executes every method held by them.
- using System;
- public delegate void MyDel();
- class Program
- {
- public void Method1()
- {
- Console.WriteLine("Method1..");
- }
- public void Method2()
- {
- Console.WriteLine("Method2..");
- }
- public void Method3()
- {
- Console.WriteLine("Method3..");
- }
- public void Method4()
- {
- Console.WriteLine("Method4..");
- }
- static void Main(string[] args)
- {
- Program p = new Program();
- MyDel del = new MyDel(p.Method1);
- del += p.Method2;
- MyDel del1 = new MyDel(p.Method3);
- del1 += p.Method4;
- del();
- del1();
- Console.ReadLine();
- }
- }
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.
- Declare a Delegate type it looks like a methods signature.
- Declare a Delegate variable of a Delegate type.
- Creates an object of a Delegate type and assign it to the Delegate variable.
- Add the methods into Delegate object (methods must have same signature and return type as the Delegate type defined in the first step).
- 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.
- Methods are held by Delegate and can be from any class or struct.
- Methods can either be the instance methods or the static methods.
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.
- 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.
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.
- MyDel del = p.Method1;
- += p.Method2;
- += p.Method3;
- += 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.
- MyDel del = p.Method1;
- += p.Method2;
- -= p.Method3;
- -= 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.
- using System;
- public delegate void MyDelegate(int a);
- class Mathematics
- {
- public void MathMethod1(int x)
- {
- Console.WriteLine("MathMethod1: returning:{0}",x+1);
- }
- public void MathMethod3(int x)
- {
- Console.WriteLine("MathMethod3: returning:{0}", x + 3);
- }
-
- public int MathMethod4(int x, int y)
- {
- return x + y;
- }
- }
-
- class Physics
- {
- public void PhysicsMethod1(int x)
- {
- Console.WriteLine("PhysicsMethod1: returning:{0}", x + 7);
- }
-
- public int PhysicsMethod3(int x, int y , int z)
- {
- return x + y + z;
- }
-
- public void PhysicsMethod2(int x)
- {
- Console.WriteLine("PhysicsMethod2: returning:{0}", x + 10);
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Mathematics m = new Mathematics();
- Physics p = new Physics();
-
- MyDelegate md = new MyDelegate(m.MathMethod1);
- md += m.MathMethod2;
- md += m.MathMethod3;
- md += p.PhysicsMethod1;
- md += p.PhysicsMethod2;
- md += p.PhysicsMethod3;
- md(2);
- Console.ReadLine();
- }
- }
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.