tags:

views:

118

answers:

2

I am talking about the common signature for events:

Event ( object, args );

and why not:

Event ( ImageProcessor, args );

Is #1 incurs a performance cost too, along with being unclear?

+4  A: 

Because an event can be raised by a number of different objects/types, and so the type may not be known at compile time.

Joel Coehoorn
Thanks Joel. You mean same event used by different types? I thought they would have their own separate events?
Joan Venge
Mainly, the same delegate type "Event" can be re-used over and over. You can also have a public event in a type that can be raised from anywhere, passing any sender, but that's a little less common.
Joel Coehoorn
How the type cannot be known at compile time. If you are not using reflection to connect event to the handler method you have all information at compile time.
SeeR
+2  A: 

I think it's because of historical reasons mixed with avoiding code duplication.

In .Net 1.0 there was no generics, so for each type that can throw event you was forced to define the event handler delegate. like:

public delegate void TextBoxEventHandler(TextBox sender, EventArgs e);
public delegate void ComboBoxEventHandler(ComboBox sender, EventArgs e);

so instead of this, freamework developers created one

public delegate void EventHandler(object sender, EventArgs e);

and used cast/as operators.

From .Net 2.0 we have generics so you can define it once like this

public delegate void EventHandler<TSender, TEventArgs>(TSender sender, TEventArgs e) where TEventArgs: EventArgs;

or even

public delegate void EventHandler<TSender, TEventArgs>(TSender sender, TEventArgs e);

And then use like this.

public event EventHandler<TextBox, string> TextChanged;
public event EventHandler<ComboBox, EventArgs> SomeComboBoxEvent;

But this would break all applications written for .Net 1.0/1.1 so instead framework developers leaved it as it was. And now everyone are using those pre-generics classes.

Also I'm not sure if Windows Forms designer can hadle generic EventHandler. I've never tried to test it.

In my opinion typed (generic) events are better than this standard. So use it where you can.

SeeR
Thanks. It makes sense. So it was a mistake then?Is it possible to use the generic version with WPF maybe?
Joan Venge
Expect problems with WPF because of XAML. I'm not the expert here. I'm still using Window Forms, but heard that in .NET 4 WPF/XAML should have much more support for generic types.
SeeR
Thanks Seer. Why did you say problems? Is it related to this exact problem or different ones?
Joan Venge
OK, I've checked it. Both Windows Forms and WPF designer works without problem with generic EventHandler. So now there is no reason to not use it :-)
SeeR