Moving Forward With .NET Events, Event-Handlers, and CustomEventArgs
In this post, we will see how some built-in types in .NET makes it easier to work with events.
Join the DZone community and get the full member experience.Join For Free
In the previous post on Events, we talked about how we are surrounded by events and how useful they can be when writing loosely coupled code. We saw how we can define events, raise, and finally handle events. If you haven’t already, then I will suggest reading that post for the background and then the topics in this post will be easier to follow.
In this post, we will continue our journey and move forward with learning more about Events implementation in .NET. One of the common requirements when raising events is how can we pass data along with event notifications to event-handlers. A very common way to do it using Custom EventArgs.
The EventArgs class is used in the signature of .NET Events. When we need to pass custom data along then EventArgs class can be extended. The following code shows that we can create a POCO style class for our custom Event data.
.NET Includes a generic EventHandler<T> class which we can use for custom EventArgs.
Raising Event With Custom EventArgs
I’ve updated the code for raising the event in the Printer class and you can see it is not much different besides the fact that we are now populating data for Custom event when raising the event.
Here is the updated code for your reference:
The mechanism for Handling customEventArgs is almost same when dealing with built-in EventArgs. I added a new class called UI and introduce a method Show which uses our custom EventArgs WorkPerformedEventArgs as shown below:
Wiring Event With EventHandler
Again, this part is also not changed and the following code shows how we now have wired the printingCompleted event with event-handler:
With all this being in place, I execute the code and the following result shows the output of execution. You will see in the output that we have now information about the CustomEventArgs data as well on the console window.
We can pass event-data to event-handlers very easily by using generic EventHandler<T> and a C# POCO class which drives from the EventArgs. I hope this will help you to think about the places in your code where you can use this functionality and it will make your code easier to understand and extend. You can see the source-code on this URL (online C# compiler) Till next time, happy coding.
Published at DZone with permission of Jawad Hasan Shani. See the original article here.
Opinions expressed by DZone contributors are their own.