tags:

views:

187

answers:

4

What's the point in the standard pattern for event delegates in .net? I.e. the EventHandler predefined delegate? Why not just choose the most appropriate signature for the requirement?

Edit: And furthermore, is it necessary to slavishly follow Microsoft's example in all cases?

+1  A: 

It decouples the caller from the callee.

jonnii
+2  A: 

It's mainly for consistency and versioning—with the sender paramater as always System.Object and the args parameter as always a System.EventArgs, or a dervied class thereof, you can change the sender argument passed to it as well as change the EventArgs type afterwards without breaking any existing code.

The whole .NET eventing idiom was designed to support component-based development, where the calling code is not under control of the developer of the component with the events.

Mark Cidade
+2  A: 

This is a good question. Heretical, but good. I read a blog post recently (I can't find the link--does anyone have that link) that debunked the myth that you need to always override System.EventArgs to provide good event handling.

I'm all for convention and following the rules, but this is one that I think can be argued to be bendable--if not avoidable. Needing to constantly override System.EventArgs for every event adds to the coupling of the routine--now there is yet another thing to keep track of.

Having an "e" that provides members isn't any more helpful or intuitive than a well-named set of arguments. I don't think the argument can be won to dispatch the recommended System.EventArg pattern, but I'd put in with you to make that argument.

rp

rp
+1  A: 

In C# 1.0 the convention didn't make a lot of sense. In C# 2.0, where there is a certain amount of delegate variance, it makes more sense.

If you have an event handling method which doesn't really care about the parameters, e.g.

public void SaveDocument(object sender, EventArgs args)
{
    // Save the document here
}

you can now use that method to subscribe to any event which follows the convention, even if the actual sender or args are more strictly typed. This means you can use the same handler for a keyboard event, a button click etc.

Jon Skeet