I just encountered an interesting Problem concerning Generics and covariance and, long story short, spent 30 minutes trying to declare a Type until i gave up.
For clarity: I already have a workaround for this, and do not need help with my project currently. I just asked this question because i am a fan of perversely complicated generic types. If you are too, enjoy.
I was trying to define this method to fetch a global IDictionary
, that manages all objects of type T
by their IDs. (IDs are only unique among objects of the same type).
IDictionary<int, T> getCache<T>() where T : BaseClass { }
To avoid checking T
for every derivative of BaseClass
(of which there are many) i wanted to define a global Dictionary of Dictionaries, to look up the correct List.
I tried something like this:
Dictionary<Type, IDictionary<int, Baseclass>> allCaches;
Expierienced users of Generics might see the problem with this implementation: the IDictionary<TKey, TValue>
interface is not covariant.
(Not covariant means, IDictionary<int, DerivedClass>
does NOT inherit from IDictionary<int, BaseClass>
. As a result, objects of the former type cannot be placed in my Dictionary allCaches
)
I ended up, just using an IDictionary<int, BaseClass>
for all my caches, and manually cast back the stored elements when i read them.
I wonder, can anyone think of an implementation for my method getCache<T>()
that uses minimal casting and does not manually branch for all types derived from BaseClass
?