Technology blog written by a Microsoft C# MVP

C#: Using Reflection to Instantiate a Generic Class in .Net

May 162007

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:

By the way, the formatting got a bit messed up in my post. Looks like using angled brackets causes a problem.

Should be:

Hi,

On line 9, you have to know at compile time that you want a List OpenAngleBracket string CloseAngleBracket.

What can you do if you only know you want string at runtime?

How can you tell the C# .NET that “o” is a List OpenAngleBracket x CloseAngleBracket where x is not known until runtime? Is there a way to access the methods of List OpenAngleBracket CloseAngleBracket from “o”?

Hi, thanks for your code first.
I encounter one similar situation recently. i need to read some configuration to load and create objects dynamically.
IPlugin is generic in my code, which is public interface IPlugin.
And concrete plugin implements IPlugin in another different assembly, which is public class ConcretePlugin : IPlugin.

in my config file, i specify the assembly name and also class name of ConcretePlugin.
In my main app, I use the following code to create instance:
Type ct = Assembly.Load(assemblyName).GetType(className);
Activator.CreateInstance(ct.MakeGenericType(typeof(int));

As it is a generic type, i have to config the class name as “ConcretePlugin`1″ rather than “ConcretePlugin”, i don’t think it is very beautiful to write configuration like this.

On line 9, you have to know at compile time that you want a List OpenAngleBracket string CloseAngleBracket.

What can you do if you only know you want string at runtime?

How can you tell the C# .NET that “o” is a List OpenAngleBracket x CloseAngleBracket where x is not known until runtime? Is there a way to access the methods of List OpenAngleBracket CloseAngleBracket from “o”?