Reputation: 8280
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?
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.
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;
}
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? :)
Upvotes: 4
Views: 219
Reputation: 700362
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.
Upvotes: 5