Introduction
Today I wanted to create a basic example about how events work in C#. This is a great tool to create loosely coupled applications, removing dependencies and allowing you to change and fix your programs making the least amount of changes.
Events
First of all we need to define three steps that we need to follow when we work with events:- We need to define a delegate with this convention:
- add the suffix "EventHandler" in the name of the envent
- Parameters: an object which is the source of the event and an EventArgs if we need to pass additional data
- Define an event based on that delegate. Note that the signature is defined by the delegate and every subscriber will have to follow that signature. Typically this has its name in past tense as it's something that already happened.
- Raise the event.
In the following example I've tried to use the analogy of a regular house with some pets and what they usually do when you get home. I've defined three classes: BreadWinner (you), Cat and Dog. There is an extra class to run the application and subscribe Dog and Cat to the event publisher, in this case, the BreadWinner.
The final step is to show you how to the same thing but using less code. .Net provides a way to prevent create a delegate every time we want to create an event by using the class EventHandler. In our example we'll use the generic class EventHandler<> as we want to pass PapaEventArgs to our subscribers. Additionally, I've added some exception handling to prevent breaking the flow when a subscriber triggers an exception. See changes highlighted.
The GREAT thing of all of this happens when there is a problem in the subscribers. Imagine this used in a very complex application and an error is raised for a subscriber. We won't need to touch the publisher and we won't need to recompile as is completely de-coupled from the rest of the subscribers.
0 comments:
Post a Comment