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\'
Here's another way which works for non-generic collections, too:
static Type GetItemType(Type collectionType)
{
return collectionType.GetMethod("get_Item").ReturnType;
}
That is, get the return type of foo[x], where foo is of the specified type.
Examples:
// Generic type; prints System.Int32
Console.WriteLine(GetItemType(typeof(List)));
// Non-generic type; prints System.String
Console.WriteLine(GetItemType(typeof(System.Collections.Specialized.StringCollection)));
The GetItemType method above has a couple issues, though:
It throws a NullReferenceException if the type has no indexing operator.
It throws an AmbiguousMatchException if the type has multiple overloads for the indexing operator (e.g. this[string] and this[int]).
Here is a more refined version:
public static Type GetItemType(this Type collectionType)
{
var types =
(from method in collectionType.GetMethods()
where method.Name == "get_Item"
select method.ReturnType
).Distinct().ToArray();
if (types.Length == 0)
return null;
if (types.Length != 1)
throw new Exception(string.Format("{0} has multiple item types", collectionType.FullName));
return types[0];
}