views:

97

answers:

1

From How to: Publish Events that Conform to .NET Framework Guidelines

Although events in classes that you define can be based on any valid delegate type, even delegates that return a value, it is generally recommended that you base your events on the .NET Framework pattern by using EventHandler, as shown in the following example.

Why? How about:

public delegate void GenericEventHandler<TType, TArgs>(TType sender, TArgs args);
public event GenericEventHandler<SomeSender, SomeArg> SomeEvent;
+2  A: 

Mainly so that any method with signature (object sender, EventArgs e) can handle your event. Keep in mind that delegates are variant (covariant return types and contravariant argument types).

Pavel Minaev
+1. you deserve it, i am not as elaborate as most people here.
Stan R.
There is value in that. However, knowing the types of your parameters seems more valuable to me.
pomeroy
I'm not sure I understand your objection. You don't usually use `EventArgs` as is, you derive a type from that, add all information this particular event will need, and use that. The event handler is free to "know the type" of that argument, or ignore it (and just accept `EventArgs`), depending on specific requirements.Or is it that you do not like the type of `sender` argument to always be `object`?
Pavel Minaev
That's true, I often see derived types of EventArgs, and that is what Microsoft encourages. If one goes to the trouble of deriving a class, it stands to reason that the event handler should accept the child class (rather than EventArgs). I find that in most situations the utility of handling the specialized event with the standard (object, EventArgs) event handler decreases.It just seems like going to more trouble than is necessary when the generic type makes it easy.
pomeroy
You can have generic types, and still stick to the pattern. Have you looked at the stock `EventHandler<T>` delegate?
Pavel Minaev
The problem with EventHandler<T> is the constraint that T : EventHandler!
pomeroy
There's no such constraint. There's a constraint that `T:EventArgs`. Why is it a problem, anyway?
Pavel Minaev
Thanks for the correction, you're right of course, EventArgs.It's an annoying constraint, and I believe the implementation still can only receive a sender of type object. Which usually requires a type cast.
pomeroy