3

I'm appalled I haven't found anything on the internet about this problem, but probably I'm looking for the wrong words. Here is what I need to do.

Suppose I have a generic type: List<string> works for the sake of simplicity. How do I get the parameter type (in this case typeof(string))?

Keep in mind that I need to do this from outside the generic class (not inside a class method, which is what I've seen in other SO questions). The bottom line is that I have an instance of a generic type, I need to know both its type AND its parameter type (in the example above, I would like to get both typeof(List) AND typeof(string), not anything like typeof(List<string>)). Of course, this must be done at runtime.

Thanks to everyone who will reply.

2
  • 1
    possible duplicate of How do I get the type argument of a generic type? Commented Jan 11, 2012 at 23:48
  • In fact, Igby. Sorry about the duplicate, I honestly couldn't find it. I looked through the similar questions proposed by the form, but couldn't find anything suitable. Thanks for the answers anyone! Commented Jan 12, 2012 at 22:01

4 Answers 4

7

It sounds like what you're looking for is Type.GetGenericArguments(). You would call it on the Type of the instance in question. It returns an array of Type (to Eric Lippert's chagrin).

Sign up to request clarification or add additional context in comments.

Comments

4
typeof(List<string>).GetGenericArguments()[0] 

Comments

2
var myList = new List<String>(); var shouldBeString = myList.GetType().GetGenericArguments().FirstOrNull(); var shouldBeGenericList = myList.GetType().GetGenericTypeDefinition(); 

See http://msdn.microsoft.com/en-us/library/system.type.getgenericarguments.aspx and http://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx respectively

1 Comment

I'm approving this one only because of its completeness, but both Harpo's and Osman's answer are equally correct. Thank you!
1

Why won't you make your function generic? It will let compiler sort it out for you.

void your_func<T>(List<T> lst) { Type list_type = typeof(List<T>); Type generic_list_type = typeof(List<>); Type generic_argument_type = typeof(T); // do what you need } 

You can invoke it like normally:

var lst = new List<string>(); // ... obj.your_func(lst); 

Other option is to use reflection as described in other answers.

2 Comments

Krizz, I don't know that the generic type will be a List. Actually I need to deal with any type, without any a priori knowledge whether it's a generic type and how many generic parameters it has. This is why I can't use this method.
Ok, I didn't get it clearly from the question. Then you definitely need to go for reflection as described in other answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.