I'm currently creating a library for fun and practice and I was wondering, when raising an event, how to choose between passing your own EventArgs derivative or just the data type.
For example, in my library I have something like this:
public delegate void LostConnectionEventHandler(string address);
public delegate void MessageReceieved(byte[] bytes);
What is the standard practice for this? Should I replace string address
with ConnectionEventArgs
and byte[] bytes
with MessageEventArgs
?
I know either one works just fine and this question may be subjective but I am still curious on the thought process higher-level programmers go through when deciding whether or not to include their own EventArgs or just to pass the data in directly.
Thanks!
Reference: http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx
Another useful information: http://msdn.microsoft.com/en-us/library/ms229011.aspx
Personally I like the idea of deriving from
EventArgs
,if you have to pass status information and aggregate objects you could easily do it, see the
MouseEventArgs type for example.
using OOP approach, if you have an event/construct which accepts an object of type
EventArgs
you can rely on the fact that every object derived from it will work in the same way while if you have another kind of object which does not share the same base class, you could eventually break something.hard to prove and reproduce but possible depending on the design, because events are special delegates designed to work with
EventArgs
and its descendantsIn a larger project, having an EventArgs class, helps with minimizing the code you have to modify, when your event needs additional data in some cases. I usually prefere the EventArgs way instead of a direct value.
Within my projects I use EventArgs when the number of parameters is larger than one! Look at the NotifyPropertyChanged Event, it has one argument, which isn't an EventArgs type.
There's no need to derive from
EventArgs
however the convention follows the common (Introduce Parameter Object) refactoring rule. And the rationale for this rule is well documented.