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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With