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

Posted by OmegaMan at May 16, 2007

Category: How To, Reflection

Tags: , ,

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

14 Comments

  1. Bishoy says

    How can we create the instance with Reflection.Emit ??

    Reply
  2. Max says

    Hi,

    thanks for this snippet. Very cool 🙂

    Cheers
    Max

    Reply
  3. Julien says

    Thanks for the snippet, it saved me some time

    Reply
  4. Johann says

    //A shortened version of the same code
    List genericList = (List)Activator.CreateInstance(typeof(List).MakeGenericType(typeof(string)));

    Reply
  5. Hossam says

    very helpful solution, thanks allot.

    Reply
  6. Matthew Brand says

    Hi,

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

    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 where x is not known until runtime? Is there a way to access the methods of List from “o”?

    Reply
  7. Matthew Brand says

    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”?

    Reply
  8. Shah says

    Thanks for the above code snippet. It is really helpful.

    Reply
  9. yanggu says

    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.

    Do u know any ways to improve this? thx.

    Reply
    • OmegaMan says

      No it sounds good. You might want to decorate your classes with custom attributes for extra info when/if needed.

      Reply
  10. Guy says

    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”?

    Reply
  11. OmegaMan says

    Once one knows the type, such as using typeof( -object goes here-), one can call the method GetGenericArguments() on its result to get its generic arguments.

    Such as this Generic method to do the same as above

    public static TPrimary Instantiate<TPrimary>() 
    {
    
        Type primary = typeof(TPrimary);
    
        var ofType  = primary.GetGenericArguments();
        var typeDef = primary.GetGenericTypeDefinition();
    
        return (TPrimary)Activator.CreateInstance(primary);
    
    }
    
    

    HTH

    Reply
  12. Vipin Chaudhary says

    Really this is a good article, which helps a lot for beginners as me as well as developer.
    This link….
    http://www.mindstick.com/Blog/165/Generic%20class%20in%20c
    also helpful to understand about generic class in C#

    Thanks.

    Reply
  13. Artak Mkrtchyan says

    Thanks for good tip. I’ve actually covered the same topic in my blog. So maybe it may be of interest: http://mkartak.blogspot.ie/2012/03/reflection-working-with-generic-types.html

    Reply

Leave a comment

(required)
(required) (will not be published)

This site uses Akismet to reduce spam. Learn how your comment data is processed.