How to get all the types of a collection that inherit from a generic class?

.net, c#, generics, reflection

Solution

AFAIK, no types report as inheriting from an open generic type: I suspect you'll have to loop manually:

static bool IsGeneric(Type type)
{
    while (type != null)
    {
        if (type.IsGenericType
            && type.GetGenericTypeDefinition() == typeof(Generic<>))
        {
            return true;
        }
        type = type.BaseType;
    }
    return false;
} 

Then the sub-list is:

var sublist = types.FindAll(IsGeneric);

or:

var sublist = types.Where(IsGeneric).ToList();

or:

foreach(var type in types) {
    if(IsGeneric(type)) {
       // ...
    }
}

Problem

I have a collection ot types: ``` List<Type> types; ``` And I want to find out which of these types inherit from a concrete generic class without caring about T: ``` public class Generic<T> ``` I've tried with: ``` foreach(Type type in types) { if (typeof(Generic<>).IsAssignableFrom(type)) { .... } } ``` But always returns false, probably due to generic element. Any ideas? Thanks in advance.

Original source