C# - Get the item type for a generic list
You could use the Type.GetGenericArguments
method for this purpose.
List<Foo> myList = ...
Type myListElementType = myList.GetType().GetGenericArguments().Single();
For a more robust approach:
public static Type GetListType(object someList)
{
if (someList == null)
throw new ArgumentNullException("someList");
var type = someList.GetType();
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(List<>))
throw new ArgumentException("Type must be List<>, but was " + type.FullName, "someList");
return type.GetGenericArguments()[0];
}
But if your variable is typed List<T>
then you can just use typeof(T)
. For example:
public static Type GetListType<T>(List<T> someList)
{
return typeof(T);
}
Note that you don't really even need the someList
parameter. This method is just an example for how you could use typeof
if you are already in a generic method. You only need to use the reflection approach if you don't have access to the T
token (the list is stored in a non-generic-typed variable, such as one typed IList
, object
, etc.).
list.GetType().GetGenericArguments()[0]