How can I see if GenericTypeDefinition implements IEnumerable<>

c#, generics, types

Solution

You can use `GetInterfaces` to check if a type implements `IEnumerable<>` like so

Type type = new List<string>().GetType();

if (type.IsGenericType) 
{
    var genericTypeDefinition = type.GetGenericTypeDefinition();

    if (genericTypeDefinition.GetInterfaces()
                .Any( t => t.IsGenericType && 
                           t.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
    {
        return type.GetGenericArguments()[0];
    }
}

Problem

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?

Original source

Related problems