k4st0r42
k4st0r42

Reputation: 1252

Get type from generic type fullname

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 ?

Upvotes: 5

Views: 5444

Answers (3)

György Kőszeg
György Kőszeg

Reputation: 18013

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

Upvotes: 3

haim770
haim770

Reputation: 49095

Try this:

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

Then use MakeGenericType():

var finalType = myType.MakeGenericType(Type.GetType("MyProject.MySimpleType"));

Alternatively, if the open generic type can be determined at compile type, you can simply use the typeof operator with <>:

var myType = typeof(MyProject.MyGenericType<>);
var finalType = myType.MakeGenericType(typeof(MyProject.MySimpleType));

See MSDN

Upvotes: 3

kiziu
kiziu

Reputation: 1130

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.

Upvotes: 3

Related Questions