Generic Type Instantiation in C#

by Donovan Olivier September 1, 2011 4:08PM

Most people know that you can get a Type object from a qualified string using the Type.GetType() method.  Let's say you have a class called MyClass in your MyAssembly assembly:

namespace MyAssembly
{
    public class MyClass
    {
        public MyClass() { }
        public string Name { get; set; }
    }
}

You can use the following call to get a System.Type instance for MyClass:

var type = System.Type.GetType("MyAssembly.MyClass,MyAssembly");

But what do you do if your class is defined with a generic type?  Let's say your class is defined like this:

namespace MyAssembly
{
    public class MyClass<T>
    {
        public MyClass() { }
        public string Name { get; set; }
        public T Data { get; set; }
    }
}

If you wanted an Type object for MyClass<string>, your natural instinct would be to try this:

var type = System.Type.GetType("MyAssembly.MyClass<string>,MyAssembly");

However, this won't work.  You need to specify the type using the following notation:

var type = System.Type.GetType("MyAssembly.MyClass`1[System.String],MyAssembly");

If your class has two generic types, like this:

namespace MyAssembly
{
    public class MyClass<T1, T2>
    {
        public MyClass() { }
        public string Name { get; set; }
        public T1 Data1 { get; set; }
        public T2 Data2 { get; set; }
    }
}

If you want MyClass<string, int>, the correct notation will now be:

var type = System.Type.GetType(
                      "MyAssembly.MyClass`2[[System.String],[System.Int32]],MyAssembly");

Tags: ,

Blog

Comments are closed

The Perpetrator

perpetrator

Donovan Olivier

software developer, architect, husband, father, son, brother, uncle, nephew, sinistral, enquirer, skeptic, cynic, anarchist, contrarian, infidel, dissident, rebel, troublemaker, dissenter, renegade.

Noise

damn this winter appetite!
planetdonovan 1 day ago

@planetdonovan it seems to be the standard ratio!
marceldupreez 1 day ago

@marceldupreez cuz there's one in every carriage ;)
planetdonovan 1 day ago

RT @marclottering: Feel like getting stoned proper today. Anyone have a COSATU connection?
planetdonovan 2 days ago

fail of the day http://t.co/7l0RI9lr
planetdonovan 4 days ago

currently suffering from severe malbeertrition.
planetdonovan 7 days ago