3

Possible Duplicates:
In a C# event handler, why must the "sender" parameter be an object?
Event Signature in .NET — Using a Strong Typed 'Sender'?

Why do all of the events in .NET have their first parameter as of type object, and not of a generic type T? Every time I have to get my sender, I have to typecast it to some more derived type. For example:

(Button)sender
Community
  • 1
  • 1
Embedd_0913
  • 16,125
  • 37
  • 97
  • 135

3 Answers3

8

Because the universal signature of event handler methods was invented long before generics were ever added to the language.

Using System.Object was the logical choice in the days before generics, as it really was the most "generic" object available. All other objects ultimately derive from System.Object, including controls, BCL classes, and user-defined classes, because it is at the root of the type hierarchy.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
2

The first reason is that this design pre-dates the introduction of generics.

But what do you think a generic approach would look like? In WinForms an OnClick event can be triggered by a Button as well as by a MenuItem. A MenuItem is not even a Control.

This event signature is used through-out the .NET library, so sender could really be anything, not just a Control or other GUI element. And the mos common class is ... System.Object.

You will have to type-cast.

H H
  • 263,252
  • 30
  • 330
  • 514
2

Strongly types senders don't work too well with inheritance hierarchies.

public class Base
{
  public event EventHandler<Base,MyEventArgs> MyEvent;
}

public class Derived:Base
{

}

Now you want to subscribe on Derived to MyEvent. Your sender will only be Base. One could work around this with new, but that gets ugly.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262