Lets say I have a List<object> which is passed into a class as an argument, this list should contain a bunch of models for my application all of the same type. Is it then possible for me to somehow retrieve the type of the list which was passed in? (without calling GetType() on a item in the list).
For example, I pass in List<User> which is stored as List<object>, can I now retrieve the type User from the list without doing something like:
List<object> aList;
aList[0].GetType();
Well, you can use:
However, that will fail if you pass in
FooListwhich derives fromList<Foo>for example. You could walk the type hierarchy and work things out appropriately that way, but it would be a pain.If at all possible, it would be better to use generics throughout your code instead, potentially making existing methods generic – e.g. instead of:
you’d have
or even
If you just need it for the very specific case where the execution-time type will always be exactly
List<T>for some list, then usingGetGenericArgumentswill work… but it’s not terribly nice.