How can I get the type of "List<String>"
in C# using Type.GetType()
?
I have already tried:
Type.GetType("List<String>");
Type.GetType("System.Collections.Generic.List.String"); // Or [String]
Note that I can't use typeof
since the value I am getting the type of is a string.
The GetType() method of array class in C# gets the Type of the current instance. To get the type. Type tp = value. GetType(); In the below example, we are checking the int value using the type.
The typeof is an operator keyword which is used to get a type at the compile-time. Or in other words, this operator is used to get the System. Type object for a type. This operator takes the Type itself as an argument and returns the marked type of the argument.
You can't get it from "List<String>"
, but you can get it from Type.GetType
:
Type type = Type.GetType("System.Collections.Generic.List`1[System.String]");
You're lucky in this case - both List<T>
and string
are in mscorlib, so we didn't have to specify the assemblies.
The `1 part specifies the arity of the type: that it has one type parameter. The bit in square brackets specifies the type arguments.
Where are you getting just List<String>
from? Can you change your requirements? It's going to be easier than parsing the string, working out where the type parameters are, finding types in different namespaces and assemblies, etc. If you're working in a limited context (e.g. you only need to support a known set of types) it may be easiest to hard-code some of the details.
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