9

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.

someone_ smiley
  • 1,006
  • 3
  • 23
  • 42

4 Answers4

12

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.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • 2
    +1. And it's not that hard to check, full name of the type (from the same assembly) can be extracted by `typeof(MyNameSpace.MyClass<>).FullName`. As far as I remember, other assemblies have full names in line of `AssemblyName+NameSpace.ClassName\`3` (for 3 generic parameters) – Patryk Ćwiek Jul 11 '13 at 09:27
  • +1. Its work like magic!!! Thank you very much :) btw, in debugger it says my class name is " MyClass`1 ". Is this normal or there is error in it? – someone_ smiley Jul 11 '13 at 09:32
  • @someone_smiley - yes, that's normal. – Damien_The_Unbeliever Jul 11 '13 at 09:34
  • Wish i could upvote more that once, thank you @Damien_The_Unbeliever – afarazit Nov 21 '20 at 15:07
7

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>

2

Is this what you are after?

    public class MyClass<T>
    {
        public T TheGeneric { get; set; }
    }


    Type theType = typeof(MyClass<>);
David Colwell
  • 2,450
  • 20
  • 31
0

try(without T):

Type template = typeof(MyNameSpace.MyClass<>);
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110