Reputation: 1337
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.
Upvotes: 3
Views: 444
Reputation: 43228
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).
Upvotes: 7
Reputation: 11552
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.
Upvotes: 1
Reputation: 51344
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
Upvotes: 2