Events and Delegates
Ali Shakkouf
ASP.NET Core Developer | Agile Development | Entity Framework, Web APIs, SQL Server
Events
Events are a mechanism for communication between objects. When something happens inside an object, it can notify other objects about it.
Why Do We Need Events?
Events are essential for building loosely coupled applications. They allow us to extend the application easily without changing or breaking existing functionalities.
Let’s break it down with a clear example:
In the example above, we are encoding a video and then sending an email to someone. There is nothing inherently wrong with this approach, but what if we decide to send a text message as well? In this case, we would need to add an additional line of code.
The problem with this approach is that when we add a new option to send a notification, we are forced to change the Encode() method. This change requires recompiling the Encode() method, the container class, and all dependent classes.
To solve this problem, we can make the Encode() method act as a publisher or event sender. It will send an event to subscribers, such as MailService and MessageService, which will act as subscribers or event receivers.
If we implement this event mechanism, the code will look like the code below
The purpose of the OnVideoEncoded() method is to notify the subscribers by sending messages to them—in other words, by invoking their methods. But how does VideoEncoder know which methods to call? We need an agreement or contract between the publisher and the subscribers.
Subscribers need to have an event handler, which is a method with the following signature:
领英推荐
The publisher knows nothing about the subscribers; all it knows is a method signature. So, how does VideoEncoder know which method to call? This is where a delegate comes in.
Here's the optimized version of the next text block:
Delegates
Delegates act as an agreement or contract between the publisher and the subscriber, determining the signature of the event handler method in the subscriber.
Returning to our example, if we want VideoEncoder to notify anyone who needs to be notified and publish an event, we need to follow three steps:
The code will look like this:
Now, we will create the subscribers, we should mention that they have same delegate signature like return type and parameters.
Then, we need to add the subscribers to the event handler like this:
And the result is: