Fun with Generics
This c++ ninja that I work with schooled me on Generics the other day. I was struggling to return a List from our EntityManager class while keeping it pretty generic. I had a property like:
public List<IEntityObject> CollectionInstance
{
get{ return new List<Customer>(); }
}
That doesn't work. I get an error about the fact that an explicit conversion exists. I spent a couple of hours trying all kinds of hacks. I guess I should know by now square peg != round hole.
The solution that Patrick (the c++ ninja) came up with was pretty simple. We templatized (he kept calling generics templates...dang c++ programmers) our EntityManager class also.
So before we had something like:
public abstract class EntityManager
{
public abstract List<IEntityObject> CollectionInstance
{
get;
}
}
and now we have:
public abstract class EntityManager<T>
{
public abstract List<T> CollectionInstance
{
get;
}
}
This allows us to refer to everything in the base class as T instead of the interface IEntityObject. This is pretty nice. Now our concrete class looks something like this:
public class CustomerManager : EntityManager<Customer>
{
public List<Customer> CollectionInstance
{
get{ return new List<Customer>; }
}
}
I really liked the way this turned out, it is much cleaner than the method I attempted and I never even considered making the manager generic.