Q:

Issue with Generics and using a run-time Type, rather than (generic) T

To lay out the problem as easily as possible, I'm trying to implement a generic pooling system that can handle an arbitrary number of concrete classes so long as they implement IBaseComponent.
So, in my class that manages the pools, I have a Dictionary of Pools:
Dictionary<Type, Pool<IBaseComponent>> pools;

As this will allow me to create as many classes that implement IBaseComponent (which is a very 'low level' interface, so to speak - so classes implementing it are not going to be compatible too terribly far) as I want, and there can be a pool for each.
Now, the issue I'm running in to is the first load of an IBaseComponent into the pool, to act as a template, so to speak.
This template object is loaded from XML, rather than code, so I do not have its actual class at compile-time, only at run time (it's defined in the XML definition and I grab the formal Type via reflection). That's all fine and dandy except, as we know, generics rely on compile-time safety.
So, using some reflection trickery I have the following:
var type = typeof(MyChildComponent);
var genericType = typeof(Pool<>);
var specificType = genericType.MakeGenericType(type);
var pool = Activator.CreateInstance(specificType );

pools.Add(T, pool as Pool<IBaseComponent>);

assuming some class:
public class MyChildComponent : IBaseComponent

The problem occurs at the last line in the first block there, when I'm adding to the pools dictionary. The cast of the instantiated pool to Pool<IBaseComponent> fails, resulting in null being inserted into the Dictionary.
My question to you fine folks is this: Is there any reasonable way around this? Any possible way, even?
If I need to load elements via some external method (XML, TXT, whatever) for at least the very first template object for a pool, for each possible concrete class that a Pool could be used for, and all I have access to is the top-level interface and formal Type of the class (both defined in the external definition file), can I do anything here?
Or is this simply not possible at all?

A:

Are you using .Net 4+?  If so, you can create an interface IPool<out T>.  The out makes the generic argument covariant, which means it will accept any version of the interface with a generic argument which is T or derives from T.
For some reason co/contravariance only works with interfaces and delegates, which is why you need IPool.
Your Dictionary will become:
Dictionary<Type, IPool<IBaseComponent>>() pools;

I'm having a little trouble combining it in my head with the reflection, but I think that should work.  If not, let me know and I'll spend a little more time on my test code.

