C# 2.0 generics
I’m playing around with C# 2.0 templates a.k.a. generics. I was really missing them in the past, but finally, they’re there.
However, the specification for C# 2.0 says in §20.1.1: A type parameter cannot be used directly to declare a base class or interface. Why such a restriction? In some cases you may be able to write your own base class, but often you’re not. If I want to extend several existing classes with some additional functionality, I can’t. Of course I could derive from each class and add my desired members, but if it’s functionality I want to add to a few classes, it’s quite impractical.
I’ve written an example. This generic would write to the console, whenever the base control is clicked:
public class ClickedControl : T where T : System.Windows.Forms.Control
{
public ClickedControl()
{
base.Click += new base_Click;
}
private void base_Click(object sender, EventArgs e)
{
Console.WriteLine(base.Text + " was clicked");
}
}
In your code you could just write
ClickedControl<System.Windows.Forms.Button> myButton;
Don’t try that home. Well, you may try it, but won’t compile. Unfortunately.
Comments
Marco Russo
Anders Hejlsberg talked about that at PDC. He said that this could be a future enhancement that could also solve most (but not all) of the need that today would require multiple inheritance.
Thomas Freudenberg
But this doesn’t involve multiple inheritance. It’s just a single base class, so I don’t see any restriction by the current CLR (i.e. Whidbey).
Gus Perez
I’d describe why we’re not doing this in Whidbey (though we’ll surely consider it for the following version), but Anders](http://www.gotdotnet.com/Community/MessageBoard/Thread.aspx?id=157521”>Anders “http://www.gotdotnet.com/Community/MessageBoard/Thread.aspx?id=157521”>Anders”) answers this exact question on the C# devcenter board.
Leave a Comment
Your email address will not be published. Required fields are marked *