Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type from generic type fullname

Tags:

c#

reflection

I would like to get type from generic type fullname like that :

var myType = Type.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]");

But it seems to not work with generics types like that...

What is the good method to do that ?

like image 880
k4st0r42 Avatar asked Sep 15 '16 08:09

k4st0r42


2 Answers

If you don't specify the assembly qualified name, Type.GetType works only for mscorlib types. In your example you has defined the AQN only for the embedded type argument.

// this returns null:
var type = Type.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]");

// but this works:
var type = Type.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");

Your original type string will work though, if you use Assembly.GetType instead of Type.GetType:

var myAsm = typeof(MyGenericType<>).Assembly;
var type = myAsm.GetType("MyProject.MyGenericType`1[[MyProject.MySimpleType, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]");
like image 112
György Kőszeg Avatar answered Oct 13 '22 21:10

György Kőszeg


The easiest way is to try "reverse engineering".

When you call eg.

typeof(List<int>)

you get

System.Collections.Generic.List`1[System.Int32]

You can then use this as a template, so calling

Type.GetType("System.Collections.Generic.List`1[System.Int32]")

will give you proper type.

Number after ` is the number of generic arguments, which are then listed in []using comma as a separator.

EDIT: If you take a look at FullName of any type, you will see how to handle types while also specifying assembly. That will require wrapping the type in extra [], so the end result would be

Type.GetType("System.Collections.Generic.List`1[[System.Int32, mscorlib]], mscorlib")

Of course, you can specify also the version, culture and public key token, if you need that.

like image 41
kiziu Avatar answered Oct 13 '22 21:10

kiziu