Generic Specialization

time to read 2 min | 360 words

It is not often that I am arriving to work and the first application that I open is Visual Studio, and I can't get it to open fast enough. Today was such a day, mostly because I got an Eureka moment. It is not often that I get those, so I really want to try it out.

Check out the following code:

public class Aggregator<T> : Aggregator<T, List<T>>

{}

 

public class Aggregator<T, TCollection>

     where TCollection : ICollection<T>, new()

{

     private ICollection<T> collection = new TCollection();

}

Can you tell why I am excited? Because this means that I have static generic specialization (I already have dynamic generic specialization, thanks to Windsor) back!

Notice that for all intents and purposes, I can either use Aggerator<T>, or use the more generic version of Aggerator<T, TCollection>, which allows me to pass my own ICollection<T> implementation.

This is actually compiler supported Inversion Of Control!

Now, of course that I can do this using ctor parameter, but this puts the burden on the client code, and couples the base implementation to the defaults. This approach keeps the base implementation frees from any default whatsoever.

I intend to make use of this soon, so I'll post about the results.