Pass An Instantiated System.Type as a Type Parameter for a Generic Class

You can’t do this without reflection. However, you can do it with reflection. Here’s a complete example:

using System;
using System.Reflection;

public class Generic<T>
    public Generic()
        Console.WriteLine("T={0}", typeof(T));

class Test
    static void Main()
        string typeName = "System.String";
        Type typeArgument = Type.GetType(typeName);

        Type genericClass = typeof(Generic<>);
        // MakeGenericType is badly named
        Type constructedClass = genericClass.MakeGenericType(typeArgument);

        object created = Activator.CreateInstance(constructedClass);

Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:

Type genericClass = typeof(IReadOnlyDictionary<,>);
Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);

Leave a Comment