DeeStackOverflow DeeStackOverflow - 2 months ago 16
C# Question

How can I get generic Type from a string representation?

I have

MyClass<T>
.

And then I have this
string s = "MyClass<AnotherClass>";
. How can I get Type from the string
s
?

One way (ugly) is to parse out the "<" and ">" and do:

Type acType = Type.GetType("AnotherClass");
Type whatIwant = typeof (MyClass<>).MakeGenericType(acType);


But is there a cleaner way to get the final type without any parsing, etc.?

Answer

The format for generics is the name, a ` character, the number of type parameters, followed by a comma-delimited list of the types in brackets:

Type.GetType("System.Collections.Generic.IEnumerable`1[System.String]");

I'm not sure there's an easy way to convert from the C# syntax for generics to the kind of string the CLR wants. I started writing a quick regex to parse it out like you mentioned in the question, but realized that unless you give up the ability to have nested generics as type parameters the parsing will get very complicated.

Comments