4

I've been wondering this for a while now; but especially more so since I've been more focused on front-end development for the last few weeks. It might sound like a broad question, but hopefully there's an answer, or a reason as to:

Why aren't .NET web control event handlers generic?

Reasoning

The reason I ask, is due to the nicety and elegance of strongly typed event handlers. Throughout my project, wherever required, I tend to use the .NET generic EventHandler<T> delegate, which has been around since .NET 2.0; as discussed here.

public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs

It would be relatively straight forward to expand on this, and to define a type for the sender as well, something like so.

public delegate void EventHandler<TSender, TArgs>(TSender sender, TArgs args) where TArgs : EventArgs

Whenever working with .NET controls, occassionally I find myself binding the event handler in the code-behind rather than the ASPX file, and then having to cast the object to the desired type if I need to do any additional checks or alterations.

Existing

Definition

public class Button : WebControl, IButtonControl, IPostBackEventHandler
{
    public event EventHandler Click;
}

Implementation

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    this.MyButton.Click += new EventHandler(MyButton_Click);
}

protected void MyButton_Click(object sender, EventArgs e)
{
    // type cast and do whatever we need to do...
    Button myButton = sender as Button;
}

Generic

Definition

public class Button : WebControl, IButtonControl, IPostBackEventHandler
{
    public event EventHandler<Button, EventArgs> Click;
}

Implementation

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    this.MyButton.Click += new EventHandler(MyButton_Click);
}

protected void MyButton_Click(Button sender, EventArgs e)
{
    // no need to type cast, yay!
}

I know it's a relatively small change, but surely it's more elegant? :)

Community
  • 1
  • 1
Richard
  • 8,110
  • 3
  • 36
  • 59

1 Answers1

5

Because it's old.

The web controls were developed for .NET 1.0, and generics didn't arrive until .NET 2.0.

Of course the controls could have been changed, but that means that all old code would need to be changed to compile (and they would need to be recompiled as the old binaries wouldn't work any more), and all old examples (millions of web pages) would be obsolete.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • In addition to the fact the controls were written before Generics existed in .NET its the simple fact Microsoft would not change existing controls in this matter. Most if not all EventHandlers are not Generic so why should a WebControl have a Generic EventHandler. – Security Hound May 29 '12 at 11:09