Wednesday, January 04, 2012

Wishlist: Derived generic parameters

In .Net generics gives a nice way to make type agnostic code that are not limited to a specific type.

The following two types are taken from the plain framework.

interface IBusinessEntity<T>{
    T Id {get;set;}
}


interface IDao<T,TT> where T : IBusinessEntity<TT>{
    T Get(TT);
    TT Save(T);
}


As shown you can use gemeric types as generic parameters for other types. In the IDao interface, I have specified that T must be a IBusinessEntity interface with the TT type as a generic parameter.
In my example I will create a Article class that implements the IBusinessEntity interface and a generic Dao implementation

class Article : IBusinessEntity<int>{
    //some code
}


class Dao<T,TT> : IDao<T,TT>{
    //some code
}



Now I want to get a dao for the class you just created. As Article has int as a generic parameter, the Dao objects has to defined with the article type as well as int to be able to compile.

var dao = new Dao<Article,int>();

Once you apply "Article", the only valid type as TT is "int". If you apply anything else, the compiler will let you know that "Article" is not valid. The reason for this is that in the definition of IDao, T has a requirement for T, not TT.
It has been bugging me that the compiler complains about the type of T and not the type of TT. T is the important generic parameter, and TT could just be derived from that.

In future releases of .net I would like to be able to write the following.
interface IDao<T<TT>> where T : IBusinessEntity<TT>{
    T Get(TT);
    TT Save(T);
}



This way I could specify TT as part of the signature, but as TT is derived from what type T is, I would only have to specify T when using it.
When creating the dao I could then write.

var dao = new Dao<Article>();

This is a small improvement, but it would remove some strange dependency error when using multiple generic parameters.

No comments:

Post a Comment