Delegates and Events in C#



Today's software is not simple anymore it must be Reliable, Scalable, and Maintainable. And no matter what you are building a Monolithic application or microservices software which is the best for embracing these concepts by making independent services that communicate via much reliable communication ensuring that communication will happen sooner or later even if other services are down. but we will discuss that in later articles after discussing more concepts that will build this knowledge and crafting this amazing skill of designing good software. but before all this, you should know the first one the primary skills: Events and Delegates.


So first of all what is an Event?


We can look at the simple button click. or we could go to a drop-down list and handle the selected index changed event, or where you might even have a custom object like an order object that when a customer places an order an event notification might go out and notify other parts of the system that hey, an order has been placed, and sending this custom object as arguments to all the other parts. And then they can act upon that to start the shipping and start the billing and all of those types of actions.


Great!.


ok, but you might ask yourself who is responsible for notifies and transferring all this information as arguments to whoever is subscribing to these events?


Congrats, you guessed it right. It's the Delegate.


In fact, without delegates, data wouldn't be transmitted from the publisher to all the subscribers. so delegate actually is the pipeline between the event and the event handlers.


so how does that delegate do that? how does it knows which functions or methods are responsible for handling events? does they all run at the same time or in sequence? And how does it transfer that data?

Delegates are just contracts that are telling you which method signature and return type is used for data to be transferred or for subscribers to subscribe for an event.


So this example here is a delegate.

public delegate void WorkPerformedHandler (int hours);

Delegates are declared outside classes, and they inherit from the Delegate or the MulticastDelegate Class (used with events ) and they are sealed classes so you are not allowed to inherit from them. but behind the scene, the compiler will generate a class for that delegate and will inherit from them and the compiler only is allowed to that, so do not try to inherit from them by yourself.


and this is how to write methods for this delegate.