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