Instantiating Generic Types at runtime

When working on my license project, I came across an uncommon case in C# where I would have to create an instance of a generic type (wich had multiple type parameters) dynamically.

Basically I had an instance of Dispatcher<A, B, C> that would be created with different type parameters A, B and C depending on the user’s selection. A and B were in my case classes of type ILoadBalancer and C a IScriptAssembler.

In order to avoid 3×3 Ifs in the code (which is actually quite dumb) I had to:

  1. Extract an simple (not generic) interface IDispatcher from Dispatcher<A, B, C> class.
  2. Instantiate the generic class at runtime:
    Type dynamicDispatcher = typeof(Dispatcher<,,>).MakeGenericType(
        new Type[] {typeof(CSharpScriptAssembler), userLocalBalancer, 
            userRemoteBalancer }
    );
    
  3. Create a new instance of the newly generated non-generic type:
    m_Dispatcher = (IDispatcher)Activator.CreateInstance(
        dynamicDispatcher,
        new Object[] { userQueueSize, userNumberOfThreads, mode }
    );
    

So, as you can see, we have to first create a non-generic type out of the generic one at runtime. And then use the Activator singleton to actually create a new instance of that type.

Points of interest:

  1. Type.MakeGenericType()
  2. Activator.CreateInstance()