Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How do I GetType of 'class with generic parameter' in run-time?

Tags:

c#

I have a generic class as shown below:

using System.Collections.Generic;

namespace MyNameSpace
{
    public class MyClass<T> : MyAnotherClass
    {
        public MyClass();
        public MyClass(T obj);
        public T Object { get; set; }
    }
}

I don't understand why following line of code return null (throwing exception with message : "Could not load type 'MyClass' from assembly '//assembly details//' ")

Type MyClassType = AssemblyContaingMyClass.GetType("MyNameSpace.MyClass");

Is it illegal to use Assembly.GetType(className) with generic class?

Can you suggest any alternate method to get type of generic class in run-time?

Thanks in advance and Apology if this question is too basic. I am new to c#.

EDIT :

Forgot to mention. the assembly containing MyClass will be loaded run-time.

like image 471
someone_ smiley Avatar asked Jul 11 '13 09:07

someone_ smiley


2 Answers

I think you have to use CLR naming to access generic types at runtime:

AssemblyContaingMyClass.GetType("MyNameSpace.MyClass`1");

In the CLR, generics are named without mentioning type parameters, but with a backtick(`) followed by the number of generic type parameters.

like image 169
Damien_The_Unbeliever Avatar answered Oct 24 '22 10:10

Damien_The_Unbeliever


The reason you cannot do this is because, simply put, there is no class named MyClass. There's the Generic Class Definition which name is something like MyClass`1, and then there's every variant of the types which name looks like MyClass`1[System.String] etc.

The easiest way to get the type is using the typeof keyword like so:

var genericType = typeof(MyClass<>);
var specificType = typeof(MyClass<string>);

However if you must load it from an assembly by its name, you need to provide the full name like so:

var genericType = assembly.GetType("MyClass`1");
var specificType = assembly.GetType("MyClass`1[System.String]");

When it comes to the naming of the generic types it's ClassName`<number of generic arguments>

like image 21
Christoffer Mansfield Avatar answered Oct 24 '22 09:10

Christoffer Mansfield