When you want to create custom events, often you need to pass an event argument, and as often you need only to pass in one parameter - your object. So what you used to do is:
public event MyCustomEventHandler MyCustomEvent; |
The not so pretty thing about it is that you had to mind-numbingly create a class which derives from EventArgs just to be able to pass your single event argument MyObject .
Now come generics and Microsoft has provided the generic type: EventHandler<TEventArgs>
and with it, you can now code
|
Well, that saved me **one ** line of code! I can ditch work early today :-)
Wouldn’t it by nice if I could cut out the whole MyCustomEventArg class? that would save some more lines of code,
and prevent my head from hitting the desk and busting my skull on an upside-down thumb tack.
Well, that’s pretty easy to do: create a new class using generics. It supports a single object as a parameter which
can be passed in at construction.
using System; |
Now the code can look like
public event MyCustomEventHandler MyCustomEvent; |
And life is good. I do have to declare the delegate though, so you daring enough to type 2 nested angled brackets, you can go for the gold:
public event EventHandler<TypedEventArg<MyObject>> MyCustomEvent; |
This lets you dispense with 1 extra line of code so for those of us typing with 1 or 2 fingers, life is better. Readability of nested generic references vs. the declaration of a delegate is a matter of taste mostly.
Taste would also guide you as to whether you like the declaration on the event consumer side better:
In case of a full delegate declaration:
Eventful eventSource = new Eventful(); |
But if a generics EventHandler is used:
eventSource.MyCustomEvent += new EventHandler<TypedEventArg<MyObject>>(classWithEvent2_SomethingHappendedEvent); |
In conclusion, by creating a simple generic type around EventArgs, I can save a few keystrokes and learn something while at it. Left as a future excercise : look at adding a constraint to the argument type such that the argument type is serializeable.