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 ?
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]]");
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.
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