Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to GetType of List<String> in C#? [duplicate]

Tags:

c#

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.

like image 206
scatman Avatar asked Jul 20 '10 06:07

scatman


People also ask

What is GetType () name in C#?

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.

Why we use typeof in C#?

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.


1 Answers

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.

like image 54
Jon Skeet Avatar answered Sep 28 '22 10:09

Jon Skeet