Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

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

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.

Upvotes: 4

Views: 100

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062895

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)) {
       // ...
    }
}

Upvotes: 6

Dennis
Dennis

Reputation: 37770

You should get first generic ancestor for the particular type in your list, and then compare generic type definition with Generic<>:

genericType.GetGenericTypeDefinition() == typeof(Generic<>)

Upvotes: 3

Related Questions