How Events And Delegates Are Related

What Is a Delegate?

In general, we call delegates function pointers,  meaning delegate object stores a reference of a method.

The delegate is a type that defines a signature, that is, the return value type and parameter list types for a method.

Delegate type can be used to declare a variable and associate its instance with any method with the same signature as the delegate then finally invoke (or call) the method through the delegate instance. Delegate allows us to implement different implementation in different methods (a kind of polymorphism - many forms)

Let’s have a look at the example to understand how delegate works.

Create a delegate that accepts two integer type variables and returns integer value.
  1. public delegate int Calculate(int x, int y);  

Define methods that have the same signature as calculate but they carry out different operations like multiplication, subtraction and addition mentioned below,

  1. public static int Multiply(int x, int y)  
  2. {  
  3.     Console.WriteLine("Hello Multiply !!");  
  4.     Console.WriteLine("Multiply {0} and {1} gives result {2}", y, x, x * y);  
  5.     return x * y;  
  6. }  
  7.   
  8. public static int Add(int x, int y)  
  9. {  
  10.     Console.WriteLine(" Add {0} and {1} gives result  {2}", y, x, x + y);  
  11.     return x + y;  
  12. }  
  13.   
  14. public static int Subtract(int x, int y)  
  15. {  
  16.     Console.WriteLine("Subtract {0} from {1} gives result  {2}", y, x, x - y);  
  17.     return x - y;  
  18. }  

Declare & create the delegate object multiplyCalculate that references the method Multiply.

  1. Calculate multiplyCalculate = new Calculate(Multiply);  

Declare & create the delegate object subtractCalculate that references the method Subtract.

  1. Calculate subtractCalculate = new Calculate(Subtract);  

Declare & create the delegate object addCalculate that references the method Add,

  1. Calculate addCalculate = new Calculate(Add);  

Invoking delegate

  1. Console.WriteLine("Invoking delegate ");  
  2. multiplyCalculate(4, 3);  
  3. subtractCalculate(4, 3);  
  4. addCalculate(4, 3);  
 Output
 
 
 
Multicast Delegate

In the above code we saw that for the delegate objects invoked one by one (in a sequential manner), at the same time .NET common language runtime allows us to combine and assign multiple objects to one delegate instance by using the += operator. The multicast delegate contains a list of the assigned delegates. When the multicast delegate is called, it invokes the delegates in the list in order they added. Only delegates of the same type can be combined.

Declare & create the delegate object of type Calculate (delegate) and later combine delegate object and assign it to

  1. Calculate calculateDelegate = new Calculate(Multiply);  
  2. calculateDelegate += new Calculate(Subtract);  
  3. calculateDelegate += new Calculate(Add);  

Invoking delegate

  1. Console.WriteLine("Invoking delegate multi-cast Delegate");  
  2. calculateDelegate(4, 3);  

Output

 

In the same way we can remove methods from the delegate instance by using -= operator

  1. calculateDelegate -= new Calculate(Subtract);  
  2. Console.WriteLine("Invoking delegate multi-cast Delegate");  
  3. calculateDelegate(5, 4);  

Output


SO far  we were using a Named method to instantiate a delegate, the named method is passed as a parameter.

Anonymous methods As Delegate

We can use another concept called anonymous methods introduced in C# 2.0 to write unnamed inline statement blocks that can be executed in a delegate invocation 

  1. Calculate multiplyAnonymousCalculate = delegate(int x, int y)  
  2. {  
  3.      Console.WriteLine("Hello Multiply !!");  
  4.      Console.WriteLine(" Multiply {0} and {1} gives result  {2}", y, x, x * y);  
  5.      return x * y;  
  6. };  
  7.   
  8. multiplyAnonymousCalculate(4, 3);  
Lambda Expression As Delegate

We can use a third concept called Lambda Expression introduced in C# 3.0 to write unnamed inline statement blocks that can be executed in a delegate invocation 

  1. Calculate multiplyAnonymousCalculate = (int x, int y) =>  
  2. {  
  3.      Console.WriteLine("Hello Multiply !!");  
  4.      Console.WriteLine(" Multiply {0} and {1} gives result  {2}", y, x, x * y);  
  5.      return x * y;  
  6.  };  
  7.   
  8.  multiplyAnonymousCalculate(4, 3);  

Delegate Accessibility

By default Delegates declared directly with a namespace are internal but can be declared as public whereas Delegates declared directly within a class are private but can be declared as public

When to use Delegates

Delegates can be used to define callback methods – using BeginInvoke method we can make an asynchronous call to perform time consuming tasks. BeginInvoke method returns a reference to an object implementing the IAsyncResult interface immediately and does not wait for the asynchronous call to complete. BeginInvoke method accepts two additional optional parameters called the callback parameter and the state parameter. Callback parameter is a reference of delegate object that will be executed when an asynchronous call or process is completed.

Now let's look at an example of defining and using a delegate to make an asynchronous call. In this example we have class or method to upload picture. Assuming that the uploading might take more time than expected, it is decided to make the method asynchronous and allow the client to provide a callback method

First define a method to upload the image

  1. public static  void UploadPicture(string imagePath)  
  2. {  
  3.     for (int iCount = 0; iCount < 10; iCount++)  
  4.     {  
  5.         Console.WriteLine("Uplodaing continues.....");  
  6.         Thread.Sleep(100);  
  7.     }  
  8. }  
Define a delegate similar to the signature of method UploadPicture,
  1. delegate void UploadPictureCallBack(string imagePath);  

Define a method to be called when asynchronous operation completed

  1. public static void UploadPictureCompleted(IAsyncResult result)  
  2. {  
  3.      if ((result != null) && (result.IsCompleted))  
  4.          Console.WriteLine("Completed");  
  5. }  

Finally make an asynchronous call and pass callback method

  1. public static void ExecuteDelegate()  
  2. {  
  3.     UploadPictureCallBack calculateDelegate = new UploadPictureCallBack(UploadPicture);  
  4.     calculateDelegate.BeginInvoke(""new AsyncCallback(UploadPictureCompleted), null);  
  5. }  

Multicasting - Sequential processing

Some time we would like to call some methods in a sequential manner which can be done by using multicast delegate. This is already explained in the multicast example shown above.

Events - Publisher subscriber model

We can use events to create a pure publisher / subscriber model. In the next section, I have explained Events and how delegate and events are associated or work together.

What Is an Event?

An event is a notification raised by one object to notify other objects that some action has happened. In C#, we define event using keyword “event” whereas in VB.Net we define event using keyword “Event” 

  1. public event EventHandler DatabaseConnectionOpened;  

If we look at the declaration, we easily make out public is the access modifier, event is the keyword used to define an event, “DatabaseConnectionOpened” is the event name but what is EventHandler?

The answer is: EventHandler is a type that represents reference to method with a particular parameter list and return type. Doesn't it look like we are talking about some specific object? Yes, it is a Delegate.

So if we look at the event declaration closely, we can say that event named “DatabaseConnectionOpened” is a type of EventHandler but that’s not true actually. EventHandler is a delegate and it is associated with the event named “DatabaseConnectionOpened” to hold a reference of a method to be called when the event is raised .

Relationship between Delegate and Event

Events are based on delegate model meaning in event based communication, one object raises the event and the other object captures and handles that event and responds to it so handler method is nothing but a method that is invoked through delegate.

Delegate helps us in connecting an event with its handler method; delegate helps us in identifying the method that provides the response to the event

.Net Common Language Runtime provides a predefined delegate named “EventHandler” delegate that specifically represents an event handler method for an event that does not generate data

Let’s have a look at the example to understand the relationship between Event and Delegates i.e., how event is declared,  delegate associated with the event, and how to raise an event and consume that event in a better way:

Use Case

Stock Exchange consolidates trading data at the end of the day, then uploads a file on the server location and finally raises an event when upload is completed to notify the users.

Option 1

When there is no need to pass data with the event, preferably use publicdelegatevoid EventHandler(object sender, EventArgs e)

  1. public class StockExchange  
  2. {  
  3.     //Event that is raised when file upload is completed  
  4.     //The EventHandler delegate is associated with the event, because no event data is provided.  
  5.     public event EventHandler FileUploaded;  
  6.       
  7.     public void ProcessData()  
  8.     {  
  9.         for (int iCount = 0; iCount <= 10; iCount++)  
  10.         {  
  11.             Console.WriteLine("Data Processing is in progress .......");  
  12.         }  
  13.         //Upload File on Server  
  14.         UploadFile();  
  15.     }  
  16.   
  17.     private void UploadFile()  
  18.     {  
  19.         Console.WriteLine("File Upload Completed");  
  20.         OnFileUploaded();  
  21.     }  
  22.   
  23.     /// <summary>  
  24.     /// Method to raise an event  
  25.     /// </summary>  
  26.     private void OnFileUploaded()  
  27.     {  
  28.  //Event raised   
  29.         FileUploaded?.Invoke(this, EventArgs.Empty);  
  30.         Console.WriteLine("Event FileUploaded raised");  
  31.     }  
  32. }  

If we look at the implementation of the above class StockExchange, we have declared an event named FileUploaded that is raised when file upload is completed. As we can see that the .NET framework in-built delegate publicdelegatevoidEventHandler(object sender, EventArgs e) is associated with the event, a method with similar signature as delegate can be declared and assigned to the event.

  1.     private static void StockExchange_FileUploaded(object sender, EventArgs e)  
  2.     {  
  3.         Console.WriteLine("StockExchange Class Event FileUploaded handled.");  
  4.     }  
  5.   
  6.          
  7.     static void Main(string[] args)          
  8.     {  
  9.            StockExchange stockExchange = new StockExchange();  
  10.            //Assign delegate object that references the method   
  11.            //StockExchange_FileUploaded to event FileUploaded  
  12.            stockExchange.FileUploaded += StockExchange_FileUploaded;  
  13.            stockExchange.ProcessData();  
  14.            Console.ReadLine();  
  15.      }  

 Output

 

Option 2

When there is a need to pass data with the event, preferably use publicdelegatevoid EventHandler<TEventArgs>(object sender, TEventArgs e) delegate instead of EventHandler TEventAgrs is the generic type and an instance of class derived from EventArgs can be assigned to it.

Let’s have a look at the example to understand how to use publicdelegatevoid EventHandler<TEventArgs>(object sender, TEventArgs e), raise an event and consume it.

Create a class to store and pass event data inheriting EventArgs, 

  1. public class FileUploadedEventArgs : EventArgs  
  2. {  
  3.     public string FileLocation { getset; }  
  4. }  

Change the current delegate and associate EventHandler<FileUploadedEventArgs> delegate with the event, because event data is to be provided when event is raised.

  1. public class StockExchange  
  2. {  
  3.     //Event that is raised when file upload is completed  
  4.     //The EventHandler delegate is associated with the event, event data is provided.  
  5.     public event EventHandler<FileUploadedEventArgs> FileUploaded;  
  6.       
  7.     public void ProcessData()  
  8.     {  
  9.         for (int iCount = 0; iCount <= 10; iCount++)  
  10.         {  
  11.             Console.WriteLine("Data Processing is in progress .......");  
  12.         }  
  13.         //Upload File on Server  
  14.         UploadFile();  
  15.     }  
  16.   
  17.     private void UploadFile()  
  18.     {  
  19.         Console.WriteLine("File Upload Completed");  
  20.         OnFileUploaded();  
  21.     }  
  22.   
  23.     /// <summary>  
  24.     /// Method to raise an event  
  25.     /// </summary>  
  26.     private void OnFileUploaded()  
  27.     {  
  28.         FileUploaded?.Invoke(thisnew FileUploadedEventArgs() {FileLocation = "\\serverIpAddresss\tradingdata.xls"});  
  29.         Console.WriteLine("Event FileUploaded raised");  
  30.     }  
  31. }  

As we can see that the .NET framework in-built delegate publicdelegatevoidEventHandler<TEventArgs>(object sender, TEventArgs e) is associated with the event, a method with similar signature as delegate can be declared and assigned to the event.

  1. private static void StockExchange_FileUploaded(object sender, FileUploadedEventArgs e)  
  2. {  
  3.     Console.WriteLine("StockExchange Class Event FileUploaded handled.");  
  4.     Console.WriteLine("File uploaded at location {0}", e.FileLocation);  
  5. }  

Output

 
 
Option 3

When there is a need to expose or make this event available to an application which does not understand or is incompatible with .NET Generics, then we can probably declare custom delegate instead of using .NET Generic delegates publicdelegatevoidEventHandler<TEventArgs>(object sender, TEventArgs e)

Let’s have a look at the example to understand how to declare custom delegate, raise an event and consume that event

Declare a custom delegate named FileUploadEventHandler 

  1. public delegate void FileUploadEventHandler(Object sender, FileUploadedEventArgs args);  
Now associate FileUploadEventHandler delegate with the event. Let’s look at the implementation,
  1. public class StockExchange  
  2. {  
  3.     //Event that is raised when file upload is completed  
  4.     //The FileUploadEventHandler delegate is associated with the event  
  5.     public event FileUploadEventHandler FileUploaded;  
  6.     
  7.     public void ProcessData()  
  8.     {  
  9.         for (int iCount = 0; iCount <= 10; iCount++)  
  10.         {  
  11.             Console.WriteLine("Data Processing is in progress .......");  
  12.         }  
  13.         //Upload File on Server  
  14.         UploadFile();  
  15.     }  
  16.   
  17.     private void UploadFile()  
  18.     {  
  19.         Console.WriteLine("File Upload Completed");  
  20.         OnFileUploaded();  
  21.     }  
  22.   
  23.     /// <summary>  
  24.     /// Method to raise an event  
  25.     /// </summary>  
  26.     private void OnFileUploaded()  
  27.     {  
  28.         Console.WriteLine("Event FileUploaded raised");  
  29.         FileUploaded?.Invoke(thisnew FileUploadedEventArgs() { FileLocation = "\\\\serverIpAddresss\\tradingdata.xls" });  
  30.     }  
  31. }  

As we can see the custom delegate publicdelegatevoidFileUploadEventHandler(Object sender, FileUploadedEventArgs args) is associated with the event, a method with a similar signature as delegate can be declared and assigned to the event.

  1. private static void StockExchange_FileUploaded(object sender, FileUploadedEventArgs e)  
  2. {  
  3.     Console.WriteLine("StockExchange Class Event FileUploaded handled.");  
  4.     Console.WriteLine("File uploaded at location {0}", e.FileLocation);  
  5. }  

 Output

 

Conclusion

Delegate is a type that defines a signature and holds a reference of method whose signature matches with the delegate.

Event is a notification raised by an object to signal the occurrence of an action. Delegate is associated with the event to hold a reference of a method to be called when the event is raised.

In the next article we will look at the Observer and Pub-Sub pattern which is based on the Event-Delegate Model.


Similar Articles