Want to show your appreciation?
Please a cup of tea.

Wednesday, June 24, 2009

How Good Is .Net Generics

People always criticize Java of not having a generics support as strong as .Net framework, which I totally agree. But in Java, I can easily specify a method parameter to take, for example, a list of T or any derived class of T. This is very usefully feature and you can see the use of this in the example below. When add, we can take any list of type T or its derived class. And we can also drainTo any list of type T or its supper class.

class MyList<T>
{
    public MyList(List<? extends T> initItems) {/*...*/}
    public void add(List<? extends T> items) {/*...*/}
    public void drainTo(List<? super T> items) {/*...*/}
}

Now, how can we do this in .Net? The closest feature to this is generic type constrain. You would probably attempt below in C#:

class MyList<T>
{
    public MyList<TDerived>(TDerived initItems) where TDerived : T {/*...*/} 
    public void Add<TDerived>(List<TDerived> items) where TDerived : T {/*...*/}
    public void DrainTo<TSuper>(List<TSuper> items) where T : TSuper {/*...*/}
}

Well, the only one actually works is the Add method. Unfortunately, the syntax is wrong for both the DrainTo method and the constructor. Constructor cannot take type parameter and the type constrain syntax is wrong in DrainTo.

I believe this is definitely the area that .Net generics support needs improvement in addition to the constrain of constrain issue. Seriously, the proper syntax for DrainTo may be more appropriate like below:

    public void DrainTo<TSuper>(List<TSuper> items) where TSuper : super T {/*...*/}

And I want type parameter in the constructors please.

No comments:

Post a Comment