ABC's of Delegate

This article helps you to understand the basics of delegate in the .NET Framework.
 

What is a Delegate?

 
In the C/C++ languages, function pointers are a buzzword; they can be used to point to a function and call the pointer in order to invoke the function. In .Net, there is nothing called pointer so .Net has delegated. In one sentence, a delegate is a glorified pointer to a function. You can call a static or instance method (function) using traditional classname.methodname or just pointing the method to delegate and call the delegate which, in turn, will call the method.
 
Delegates provide a mechanism for defining and executing callbacks. This allows you to define the exact signature of a callback and that defines the type of delegate. In general, delegate instances consist of fields like a reference to an object and a pointer to an instance method. However, if the object reference is null, CLR understands it as a static method.
 
When you declare a delegate, the C# compiler generates a class derived from MulticastDelegate. MulticastDelegate contains several methods but you cannot see those methods if you view the IL of your code in ILDASM. It is because CLR implements all these methods dynamically at runtime.
 
Delegate allows classes to not be coupled strongly. Also, the caller of the delegate has no idea whether it is calling a static method or instance method or what exact method it is calling. Think about the GUI Button class. Button class doesn't know which method it will execute onClick event. Just think, if we write the code within the button class OnClick event, then would it be a reusable class? Button class publishes the OnClick event using a delegate and specifies that you can subscribe to the OnClick event with a method. In this way, you can de-couple your classes using a delegate.
 

How to call Delegate

 
Before delving into code, you need to understand one very simple rule about delegates. The return-type or parameter list of the method that you want to reference by the delegate should match with the delegate type declaration. Confused! Take an example
 
Suppose I have one method like void PrintToConsole(string message). The delegate type should be delegate void objDelegate(string message). Now if you write objDelegate = PrintToConsole then it is perfect. Call the function using objDelegate("Hello World") which will execute the PrintToConsole method.
 
So what does the following statement mean?
  1. public delegate void _delegate(int i, int j);  
It means a declaration of delegate that can encapsulate any method which will take two integer parameters and return void.
 
When you declare the above line, the C# compiler produces the following code snippet
  1. public class NotifyGpaDelegate: System.MulticastDelegate {  
  2.     public void Invoke(int GPAScore) {  
  3.         // code  
  4.     }  
This Invoke method is part of MulticastDelegate and should have the same signature as the defined delegate.
 

Simple Delegate

  1. public delegate void _MathDelegate(int x, int y);  
  2. public class clsMath {  
  3.   public void Sum(int i, int j) {  
  4.     Console.WriteLine(i + j);  
  5.   }  
  6.   public static void Subtract(int i, int j) {  
  7.     Console.WriteLine(i - j);  
  8.   }  
  9. }  
  10. class Program {  
  11.   static void Main(string[] args) {  
  12.     clsMath _math = new clsMath();  
  13.     _MathDelegate _delegate1, _delegate2;  
  14.     _delegate1 = _math.Sum;  
  15.     _delegate2 = clsMath.Subtract;  
  16.     _delegate1(100, 50);  
  17.     _delegate2(100, 50);  
  18.   }  
In the above code, I defined a delegate that returns void and takes two integer parameters. Since I want to call the Sum/Subtract method using this delegate, you can see I have made the signature compatible between delegate and Sum/Subtract method. In my main method, I declared the delegates, referenced the delegates with the methods, and called the delegates, which in turn calls the methods. This is an example of a simple delegate
 

Delegate Chaining

 
It means you can maintain a list of delegates which can be called. Internally it maintains a linked list of delegates and when the head of the list is called, all the delegates in the chain are called. In the Delegate class, the following methods help to form a delegate chain.
  1. public abstract class Delegate : ICloneable, ISerializable  
  2. {  
  3.     public static Delegate Combine(params Delegate[] delegates);  
  4.     public static Delegate Combine(Delegate a, Delegate b);  
  5. }  
The first method takes an array of delegates and returns a delegate type. You can also remove the delegate from the delegate chain using the following methods defined in the Delegate class
  1. public abstract class Delegate : ICloneable, ISerializable  
  2. {  
  3.     public static Delegate Remove(Delegate source, Delegate value);  
  4.     public static Delegate RemoveAll(Delegate source, Delegate value);  
  5. }  
The source is the delegate chain and value is the delegate that you want to remove from the delegate chain.
 
In order to make programming simple, the C# compiler uses operator overloading to implement these methods. You can use + to combine and – to remove from the delegate chain.
  1. public delegate void _MathDelegate(int x,int y);  
  2. public class clsMath  
  3. {  
  4.     public void Sum(int i, int j)  
  5.     {  
  6.         Console.WriteLine(i + j);  
  7.     }  
  8.     public static void Subtract(int i, int j)  
  9.     {  
  10.         Console.WriteLine(i - j);  
  11.     }        
  12. }  
  13. class Program  
  14. {         
  15.    static void Main(string[] args)  
  16.     {  
  17.        clsMath _math = new clsMath();  
  18.        _MathDelegate[] _delegate = new _MathDelegate[]{_math.Sum,clsMath.Subtract};  
  19.        _MathDelegate _chainDelegate = _delegate[0] + _delegate[1];  
  20.        _chainDelegate(100, 50);  
  21.     }  
  22. }  
In the above example, I define one array of delegates that contains all instance and static methods. You can combine those methods using the + operator which will call Sum and Subtract method respectively.
  1. _MathDelegate _chainDelegate = _delegate[0] + _delegate[1];  
  2. _MathDelegate _chainDelegate1 = _chainDelegate - _delegate[0];  
If I use the above two statements, CLR interprets it as (Sum + Subtract) - Sum and executes only the Subtract method. This is an example of removing delegates from the delegate chain using - operator.
 
You can also iterate through the delegate chain.
  1. public delegate int _MathDelegate(int x,int y);  
  2. public class clsMath  
  3. {  
  4.     public int Sum(int i, int j)  
  5.     {  
  6.         return (i + j);  
  7.     }  
  8.     public static int Subtract(int i, int j)  
  9.     {  
  10.         return (i - j);  
  11.     }        
  12. }  
  13. class Program  
  14. {         
  15.    static void Main(string[] args)  
  16.     {  
  17.         int iTemp = 0;  
  18.        clsMath _math = new clsMath();  
  19.        _MathDelegate[] _delegate = new _MathDelegate[]{_math.Sum,clsMath.Subtract};  
  20.        _MathDelegate _chainDelegate = _delegate[0] + _delegate[1];  
  21.        Delegate[] _delegates = _chainDelegate.GetInvocationList();  
  22.        for (int i = 0; i < _delegates.Length; i++)  
  23.        {  
  24.            _MathDelegate _del = (_MathDelegate)_delegates[i];  
  25.            iTemp += _del(100, 50);  
  26.        }  
  27.        Console.WriteLine(iTemp);            
  28.     }  
  29. }  
In the above example, I used the GetInvocationList method to get all the delegates in the delegate chain and call each delegate and summed it up. This method helps us to reference each delegate in the delegate chain and we can also call delegates from the delegate chain in any order.
 

What is Multicast Delegate?

 
A delegate can call more than one method when invoked. This is referred to as multicasting. A useful property of delegate objects is that they can be assigned to one delegate instance to be multicast using the + operator. A composed delegate calls the two delegates it was composed of. Only delegates of the same type can be composed. The - operator can be used to remove a component delegate from a composed delegate. Also, the multicast delegate return type is always void.
 
We can change the implementation of the above code because the Multicast Delegate return type should be void.
 
An Example
  1. class Program {  
  2.     // Simple Sum method  
  3.     public static void Sum(int i, int j) {  
  4.         Console.WriteLine(i + j);  
  5.     }  
  6.     // Simple Subtract method  
  7.     public static void Subtract(int i, int j) {  
  8.         Console.WriteLine(i - j);  
  9.     }  
  10.     // Declaring a simple delegate which will  
  11.     // encapsulate a Sum/Subtract method  
  12.     public delegate void _delegate(int x, int y);  
  13.     static void Main(string[] args) {  
  14.         // Declaring objects of Delegate  
  15.         _delegate objDelegate1, objDelegate2, objDelegate3, objDelegate4;  
  16.         // Referencing Sum by the delegate object  
  17.         objDelegate1 = Sum;  
  18.         // Referencing Subtract by the delegate object  
  19.         objDelegate2 = Subtract;  
  20.         // This will call Sum and Subtract both  
  21.         objDelegate3 = objDelegate1 + objDelegate2;  
  22.         objDelegate3(100, 50);  
  23.         // This will call only Subtract  
  24.         objDelegate4 = objDelegate3 - objDelegate2;  
  25.         objDelegate4(100, 50);  
  26.     }  
objDelegate3 = objDelegate1 + objDelegate2 means it will call Sum and Subtract method both.
 
objDelegate4 = objDelegate3 - objDelegate2 means (Sum + Subtract) – Subtract, which means that call to Sum then Subtract and then Sum again.
 
A few basic things about Delegates
  • Delegates are object-oriented, type-safe, and secure.
  • Delegate types are derived from the Delegate class in .NET.
  • Delegate types are sealed so you cannot inherit from Delegate.


Recommended Free Ebook
Similar Articles