DeeStackOverflow DeeStackOverflow - 1 year ago 77
C# Question

How can I get generic Type from a string representation?

I have


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

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 Source

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:


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.