Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.?

like image 844
DeeStackOverflow Avatar asked Apr 06 '09 15:04

DeeStackOverflow


People also ask

How do you find the type of generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

Is it possible to inherit from a generic type?

You can't inherit from a Generic type argument. C# is strictly typed language. All types and inheritance hierarchy must be known at compile time. . Net generics are way different from C++ templates.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

Is any a generic type?

Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.


2 Answers

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.

like image 148
Neil Williams Avatar answered Sep 21 '22 12:09

Neil Williams


Check out Activator.CreateInstance - you can call it with a type

Activator.CreateInstance(typeof(MyType)) 

or with an assembly and type name as string

Activator.CreateInstance("myAssembly", "myType") 

This will give you an instance of the type you need.

If you need the Type rather than the instance, use the Type.GetType() method and the fully qualified name of the type you're interested in, e.g.:

string s = "System.Text.StringBuilder"; Type myClassType = Type.GetType(s); 

That'll give you the Type in question.

like image 21
marc_s Avatar answered Sep 20 '22 12:09

marc_s