C# .NET Delegates and Events


In this article, you will learn how to create and manipulate delegate types as well as C# events that streamline the process of working with delegate types.

Delegates provide a way to define and execute callbacks. Their flexibility allows you to define the exact signature of the callback, and that information becomes part of the delegate type itself. Delegates are type-safe, object-oriented and secure.

Delegates Overview

A Delegate is an abstraction of one or more function pointers (as existed in C++; the explanation about this is out of the scope of this article). The .NET has implemented the concept of function pointers in the form of delegates. With delegates, you can treat a function as data. Delegates allow functions to be passed as parameters, returned from a function as a value and stored in an array. Delegates have the following characteristics:

  • Delegates are derived from the System.MulticastDelegate class.
  • They have a signature and a return type. A function that is added to delegates must be compatible with this signature.
  • Delegates can point to either static or instance methods.
  • Once a delegate object has been created, it may dynamically invoke the methods it points to at runtime.
  • Delegates can call methods synchronously and asynchronously.

The delegate contains a couple of useful fields. The first one holds a reference to an object, and the second holds a method pointer. When you invoke the delegate, the instance method is called on the contained reference. However, if the object reference is null then the runtime understands this to mean that the method is a static method. Moreover, invoking a delegate syntactically is the exact same as calling a regular function. Therefore, delegates are perfect for implementing callbacks.

Why Do We Need Delegates

Historically, the Windows API made frequent use of C-style function pointers to create callback functions. Using a callback, programmers were able to configure one function to report back to another function in the application. So the objective of using a callback is to handle button-clicking, menu-selection, and mouse-moving activities. But the problem with this traditional approach is that the callback functions were not type-safe. In the .NET framework, callbacks are still possible using delegates with a more efficient approach. Delegates maintain three important pieces of information, as in the following;

  • The parameters of the method.
  • The address of the method it calls.
  • The return type of the method.

A delegate is a solution for situations in which you want to pass methods around to other methods. You are so accustomed to passing data to methods as parameters that the idea of passing methods as an argument instead of data might sound a little strange. However, there are cases in which you have a method that does something, for instance, invoking some other method. You do not know at compile time what this second methods is. That information is available only at runtime hence Delegates are the device to overcome such complications.

Defining a Delegate

A Delegate can be defined as a delegate type. Its definition must be similar to the function signature. A delegate can be defined in a namespace and within a class. A delegate cannot be used as a data member of a class or local variable within a method. The prototype for defining a delegate type is as the following;

accessibility delegate return type delegatename(parameterlist);

Delegate declarations look almost exactly like abstract method declarations, you just replace the abstract keyword with the delegate keyword. The following is a valid delegate declaration:

  1. public delegate int operation(int x, int y);   
When the C# compiler encounters this line, it defines a type derived from MulticastDelegate, that also implements a method named Invoke that has exactly the same signature as the method described in the delegate declaration. For all practical purposes, that class looks like the following:
  1. public class operation : System.MulticastDelegate  
  2. {  
  3.     public double Invoke(int x, int y);  
  4.     // Other code  
  5. }  
As you can see using ILDASM.exe, the compiler generated operation class defines three public methods as in the following:

                                                          Figure 1.1

After you have defined a delegate, you can create an instance of it so that you can use it to store the details of a particular method.

Delegates Sample Program

The delegate implementation can cause a great deal of confusion when encountered the first time. Thus, it is a great idea to get an understanding by creating this sample program as: 
  1. using System;  
  3. namespace Delegates  
  4. {  
  5.     // Delegate Definition  
  6.     public delegate int operation(int x, int y);  
  8.     class Program  
  9.     {  
  10.         // Method that is passes as an Argument  
  11.         // It has same signature as Delegates   
  12.         static int Addition(int a, int b)  
  13.         {  
  14.             return a + b;  
  15.         }  
  17.         static void Main(string[] args)  
  18.         {  
  19.             // Delegate instantiation  
  20.             operation obj = new operation(Program.Addition);  
  22.             // output  
  23.             Console.WriteLine("Addition is={0}",obj(23,27));   
  24.             Console.ReadLine();    
  25.         }  
  26.     }  
  27. }  

Here, we are defining the delegate as a delegate type. The important point to remember is that the signature of the function reference by the delegate must match the delegate signature as:

  1. // Delegate Definition  
  2. public delegate int operation(int x, int y);  
Notice the format of the operation delegate type declaration; it specifies that the operation object can permit any method taking two integers and returning an integer. When you want to insert the target methods to a given delegate object, simply pass in the name of the method to the delegate constructor as: 
  1. // Delegate instantiation  
  2. operation obj = new operation(Program.Addition);  
At this point, you are able to invoke the member pointed to using a direct function invocation as:
  1. Console.WriteLine("Addition is={0}",obj(23,27));   
Finally, when the delegate is no longer required, set the delegate instance to null.

Recall that .NET delegates are type-safe. Therefore, if you attempt to pass a delegate a method that does not match the signature pattern, the .NET will report a compile-time error.

Array of Delegates

Creating an array of delegates is very similar to declaring an array of any type. The following example has a couple of static methods to perform specific math related operations. Then you use delegates to call these methods. 
  1. using System;  
  3. namespace Delegates  
  4. {  
  5.     public class Operation  
  6.     {  
  7.         public static void Add(int a, int b)  
  8.         {  
  9.             Console.WriteLine("Addition={0}",a + b);  
  10.         }  
  12.         public static void Multiple(int a, int b)  
  13.         {  
  14.             Console.WriteLine("Multiply={0}", a * b);  
  15.         }  
  16.     }   
  18.     class Program  
  19.     {  
  20.         delegate void DelOp(int x, int y);  
  22.         static void Main(string[] args)  
  23.         {  
  24.             // Delegate instantiation  
  25.             DelOp[] obj =   
  26.            {  
  27.                new DelOp(Operation.Add),  
  28.                new DelOp(Operation.Multiple)  
  29.            };  
  31.             for (int i = 0; i < obj.Length; i++)  
  32.             {  
  33.                 obj[i](2, 5);  
  34.                 obj[i](8, 5);  
  35.                 obj[i](4, 6);  
  36.             }  
  37.             Console.ReadLine();  
  38.         }  
  39.     }  
  40. }  

In this code, you instantiate an array of Delop delegates. Each element of the array is initialized to refer to a different operation implemented by the operation class. Then, you loop through the array, apply each operation to three different values. After compiling this code, the output will be as follows;

                                                Figure 1.2

Anonymous Methods

Anonymous methods, as their name implies, are nameless methods. They prevent creation of separate methods, especially when the functionality can be done without a new method creation. Anonymous methods provide a cleaner and convenient approach while coding.

Define an anonymous method with the delegate keyword and a nameless function body. This code assigns an anonymous method to the delegate. The anonymous method must not have a signature. The signature and return type is inferred from the delegate type. For example if the delegate has three parameters and return a double type, then the anonymous method would also have the same signature.

  1. using System;  
  3. namespace Delegates  
  4. {  
  5.     class Program  
  6.     {  
  7.         // Delegate Definition  
  8.         delegate void operation();  
  10.         static void Main(string[] args)  
  11.         {  
  12.             // Delegate instantiation  
  13.             operation obj = delegate  
  14.             {  
  15.                 Console.WriteLine("Anonymous method");  
  16.             };  
  17.             obj();  
  19.             Console.ReadLine();  
  20.         }  
  21.     }  
  22. }  

The anonymous methods reduce the complexity of code, especially where there are several events defined. With the anonymous method, the code does not perform faster. The compiler still defines methods implicitly.

Multicast Delegate

So far, you have seen a single method invocation/call with delegates. If you want to invoke/call more than one method, you need to make an explicit call through a delegate more than once. However, it is possible for a delegate to do that via multicast delegates. 

A multicast delegate is similar to a virtual container where multiple functions reference a stored invocation list. It successively calls each method in FIFO (first in, first out) order. When you wish to add multiple methods to a delegate object, you simply make use of an overloaded += operator, rather than a direct assignment.

  1. using System;  
  3. namespace Delegates  
  4. {  
  5.     public class Operation  
  6.     {  
  7.         public static void Add(int a)  
  8.         {  
  9.             Console.WriteLine("Addition={0}", a + 10);  
  10.         }  
  11.         public static void Square(int a)  
  12.         {  
  13.             Console.WriteLine("Multiple={0}",a * a);  
  14.         }  
  15.     }  
  16.     class Program  
  17.     {  
  18.         delegate void DelOp(int x);  
  20.         static void Main(string[] args)  
  21.         {  
  22.             // Delegate instantiation  
  23.             DelOp obj = Operation.Add;  
  24.             obj += Operation.Square;  
  26.             obj(2);  
  27.             obj(8);  
  29.             Console.ReadLine();  
  30.         }  
  31.     }  
  32. }  

The code above combines two delegates that hold the functions Add() and Square(). Here the Add() method executes first and Square() later. This is the order in which the function pointers are added to the multicast delegates.

To remove function references from a multicast delegate, use the overloaded -= operator that allows a caller to dynamically remove a method from the delegate object invocation list.

  1. // Delegate instantiation  
  2. DelOp obj = Operation.Add;  
  3. obj -= Operation.Square;  
Here when the delegate is invoked, the Add() method is executed but Square() is not because we unsubscribed it with the -= operator from a given runtime notification.

Invoking multiple methods by one delegate may lead into a problematic situation. If one of the methods invoked by a delegate throws an exception, then the complete iteration would be aborted. You can avoid such a scenario by iterating the method invocation list on your own. The Delegate class defines a method GetInvocationList that returns an array of Delegate objects. 
  1. using System;  
  3. namespace Delegates  
  4. {  
  5.     public class Operation  
  6.     {  
  7.         public static void One()  
  8.         {  
  9.             Console.WriteLine("one display");  
  10.             throw new Exception("Error");   
  11.         }  
  12.         public static void Two()  
  13.         {  
  14.             Console.WriteLine("Two display");  
  15.         }  
  16.     }  
  18.     class Program  
  19.     {  
  20.         delegate void DelOp();  
  22.         static void Main(string[] args)  
  23.         {  
  24.             // Delegate instantiation  
  25.             DelOp obj = Operation.One;  
  26.             obj += Operation.Two;  
  28.             Delegate[] del = obj.GetInvocationList();  
  30.             foreach (DelOp d in del)  
  31.             {  
  32.                 try  
  33.                 {  
  34.                     d();  
  35.                 }  
  36.                 catch (Exception)  
  37.                 {  
  38.                     Console.WriteLine("Error caught");  
  39.                 }  
  40.             }  
  41.             Console.ReadLine();  
  42.         }  
  43.     }  
  44. }  

When you run the application, you will see that the iteration still continues with the next method even after an exception is caught as in the following.

                                                Figure 1.3


The applications and windows communicate via predefined messages. These messages contain various pieces of information to determine both window and application actions. The .NET considers these messages as an event. If you need to react to a specific incoming message then you would handle the corresponding event. For instance, when a button is clicked on a form, Windows sends a WM_MOUSECLICK message to the button message handler.

You don't need to build custom methods to add or remove methods to a delegate invocation list. C# provides the event keyword. When the compiler processes the event keyword, you can subscribe and unsubscribe methods as well as any necessary member variables for your delegate types. The syntax for the event definition should be as in the following:

Accessibility event delegatename eventname;

Defining an event is a two-step process. First, you need to define a delegate type that will hold the list of methods to be called when the event is fired. Next, you declare an event using the event keyword. To illustrate the event, we are creating a console application. In this iteration, we will define an event to add that is associated to a single delegate DelEventHandler.

  1. using System;  
  3. namespace Delegates  
  4. {  
  5.     public delegate void DelEventHandler();  
  7.     class Program  
  8.     {  
  9.         public static event DelEventHandler add;  
  11.         static void Main(string[] args)  
  12.         {  
  13.             add += new DelEventHandler(USA);  
  14.             add += new DelEventHandler(India);  
  15.             add += new DelEventHandler(England);  
  16.             add.Invoke();  
  18.             Console.ReadLine();  
  19.         }  
  20.         static void USA()  
  21.         {  
  22.             Console.WriteLine("USA");    
  23.         }  
  25.         static void India()  
  26.         {  
  27.             Console.WriteLine("India");  
  28.         }  
  30.         static void England()  
  31.         {  
  32.             Console.WriteLine("England");  
  33.         }  
  34.     }  
  35. }  

In the main method, we associate the event with its corresponding event handler with a function reference. Here, we are also filling the delegate invocation lists with a couple of defined methods using the +=operator as well. Finally, we invoke the event via the Invoke method.

Note: Event Handlers can't return a value. They are always void.

Let's use another example to get the better understanding of events. Here we are defining an event name as xyz and a delegate EventHandler with a string argument signature in the operation class. We are putting the implementation in the action method to confirm whether an event is fired or not.

  1. using System;  
  3. namespace Delegates  
  4. {  
  5.     public delegate void EventHandler(string a);  
  7.     public class Operation  
  8.     {  
  9.         public event EventHandler xyz;  
  11.         public void Action(string a)  
  12.         {  
  13.             if (xyz != null)  
  14.             {  
  15.                 xyz(a);  
  16.                 Console.WriteLine(a);   
  17.             }  
  18.             else  
  19.             {  
  20.                 Console.WriteLine("Not Registered");   
  21.             }  
  22.         }  
  23.     }  
  25.     class Program  
  26.     {  
  27.         public static void CatchEvent(string s)  
  28.         {  
  29.             Console.WriteLine("Method Calling");  
  30.         }  
  32.         static void Main(string[] args)  
  33.         {  
  34.             Operation o = new Operation();  
  36.             o.Action("Event Calling");   
  37.             o.xyz += new EventHandler(CatchEvent);  
  39.             Console.ReadLine();  
  40.         }  
  41.     }  
  42. }  

Later in the Program class, we are defining a CatchEvent method that would be referenced in the delegate invocation list. Finally, in the main method, we instantiated the operation class and put in the event firing implementation.

Finally we are elaborating on the events with a realistic example of creating a custom button control over the Windows form that would be called from a console application. First, we inherit the program class from the Form class and define its associated namespace at the top. Thereafter, in the program class constructor, we are crafting a custom button control.

  1. using System;  
  2. using System.Drawing;  
  3. using System.Windows.Forms;  
  5. namespace Delegates  
  6. {  
  7.     //custom delegate  
  8.     public delegate void DelEventHandler();  
  10.     class Program :Form   
  11.     {  
  12.         //custom event  
  13.         public event DelEventHandler add;  
  15.         public Program()  
  16.         {  
  17.             // desing a button over form  
  18.             Button btn = new Button();  
  19.             btn.Parent = this;  
  20.             btn.Text = "Hit Me";  
  21.             btn.Location = new Point(100,100);  
  23.             //Event handler is assigned to  
  24.             // the button click event  
  25.             btn.Click += new EventHandler(onClcik);  
  26.             add += new DelEventHandler(Initiate);  
  28.             //invoke the event  
  29.             add();  
  30.         }  
  31.         //call when event is fired  
  32.         public void Initiate()  
  33.         {  
  34.             Console.WriteLine("Event Initiated");  
  35.         }  
  37.         //call when button clicked  
  38.         public void onClcik(object sender, EventArgs e)  
  39.         {  
  40.             MessageBox.Show("You clicked me");    
  41.         }  
  42.         static void Main(string[] args)  
  43.         {  
  44.             Application.Run(new Program());  
  46.             Console.ReadLine();  
  47.         }  
  48.     }  
  50. }  

We are calling the Windows Form by using the Run method of the Application class. Finally when the user runs this application, first the Event fired message will be displayed on the screen and a Windows Form with the custom button control. When the button is clicked, a message box will be shown as in the following;

                                                               Figure 1.4