I have a method that checks if a type is generic and then checks if the GenericTypeDefinition is of IEnumerable<>
.
static Type GetEnumerableType(Type type)
{
if(type.IsGenericType) {
var genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(IEnumerable<>)) {
return type.GetGenericArguments()[0];
}
}
return null;
}
Works like a charm if it is an IEnumerable. If the the GenericTypeDefinition is IList<>
or List<>
it doesn't work. I've tried..
typeof(IEnumerable<>).IsAssignableFrom(genericTypeDefinition)
..without success. Of course there must be a better way then chaining else-statements?