Sonny Boy Sonny Boy - 1 year ago 94
C# Question

C# - Get the item type for a generic list

What would be the best way of getting the type of items a generic list contains? It's easy enough to grab the first item in the collection and call .GetType(), but I can't always be sure there will be an item in the collection.

Hope that makes sense.



Ani Ani
Answer Source

You could use the Type.GetGenericArguments method for this purpose.

List<Foo> myList = ...

Type myListElementType = myList.GetType().GetGenericArguments().Single();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download