Events in C#: Let’s Party

What do I think about events in C#? I think they are not so different from what we have in real life. And when we have an event, we need to think of three things: who is the host, who are the guests, and what do we need to put onto the invitation cards.
Let me start with the invitation cards.
In C#, we form a particular class that inherits from EventArgs and contains all the information that a party host wants to transfer to guests.
PartEventsArgs
Another class that we need to create will represent the party host. It has two responsibilities.
First, it informs other classes on how to consume the events. In other words, it defines the signature of the event handler.
Second, it has a protected virtual method that invokes event handlers of all the registered guests.
PartyHost
The last class we are going to design is the guest. The guests’ responsibility is reacting to invitations.
PartyGuest
Finally, we are creating instances of the described classes and register guests so they can receive the party host’s invitations.
Program
When we run the program, the party guest’s invitation handler works.
Output
Conclusion:

Using events in C# is quite simple and allows us to decouple classes very well.

Leave a Reply

Your email address will not be published.