Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 402
Ignacio Soler Garcia Avatar asked Jan 11 '23 18:01

Ignacio Soler Garcia


2 Answers

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)) {
       // ...
    }
}
like image 127
Marc Gravell Avatar answered Jan 14 '23 07:01

Marc Gravell


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<>)
like image 41
Dennis Avatar answered Jan 14 '23 07:01

Dennis