getting type T from IEnumerable<T>
IEnumerable<T> myEnumerable;
Type type = myEnumerable.GetType().GetGenericArguments()[0];
Thusly,
IEnumerable<string> strings = new List<string>();
Console.WriteLine(strings.GetType().GetGenericArguments()[0]);
prints System.String
.
See MSDN for Type.GetGenericArguments
.
Edit: I believe this will address the concerns in the comments:
// returns an enumeration of T where o : IEnumerable<T>
public IEnumerable<Type> GetGenericIEnumerables(object o) {
return o.GetType()
.GetInterfaces()
.Where(t => t.IsGenericType
&& t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.Select(t => t.GetGenericArguments()[0]);
}
Some objects implement more than one generic IEnumerable
so it is necessary to return an enumeration of them.
Edit: Although, I have to say, it's a terrible idea for a class to implement IEnumerable<T>
for more than one T
.
I'd just make an extension method. This worked with everything I threw at it.
public static Type GetItemType<T>(this IEnumerable<T> enumerable)
{
return typeof(T);
}
I had a similar problem. The selected answer works for actual instances.
In my case I had only a type (from a PropertyInfo
).
The selected answer fails when the type itself is typeof(IEnumerable<T>)
not an implementation of IEnumerable<T>
.
For this case the following works:
public static Type GetAnyElementType(Type type)
{
// Type is Array
// short-circuit if you expect lots of arrays
if (type.IsArray)
return type.GetElementType();
// type is IEnumerable<T>;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (IEnumerable<>))
return type.GetGenericArguments()[0];
// type implements/extends IEnumerable<T>;
var enumType = type.GetInterfaces()
.Where(t => t.IsGenericType &&
t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.Select(t => t.GenericTypeArguments[0]).FirstOrDefault();
return enumType ?? type;
}