Reflection has many purposes, but what happens if one wants to instantiate a generic class? How does one specify the what makes the class generic to  instantiate it? The trick is to use the MakeGenericType to make the argument(s) and then call create Instance. Here is a code snippet:

Type d1 = typeof(List<>);

Type[] typeArgs = { typeof(string) };

Type makeme = d1.MakeGenericType(typeArgs);

object o = Activator.CreateInstance(makeme);

List<string> itsMe = o as List<string>;

Console.WriteLine((itsMe == null) ? "Failed" : "Succeeded");

Here is what is going on

  • Line 1 We get the type as normal.
  • Line 3 Create an array of the arguments we are interested in.
  • Line 5 Call MakeGenericType to do the magic
  • Line 7 Create the object.
Share