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");