How to filter a parameterized type regardless of its parameter types?

I want to know if the type is IQueryable.

var t = typeof(IQueryable<int>);
bool isQueryable = (t is IQueryable); // false
bool isAssignableFrom = t.IsAssignableFrom(typeof(IQueryable)); // false
bool nameStartsWithIQueryable = t.Name.StartsWith("IQueryable"); // true

The third way - looking at the beginning of a type name - works, but feels like a hack.

Is there any other way to do this?

+3
source share
2 answers

Use GetGenericTypeDefinition:

bool isQueryable = t.GetGenericTypeDefinition() == typeof(IQueryable<>);

If you need to handle deeper ancestors (where you check the type of base type aganist), you can write a helper method:

public static bool IsType(Type type, Type ancestor)
{
    while (type != null)
    {
        if (type.IsGenericType)
            type = type.GetGenericTypeDefinition();
        if (type == ancestor)
            return true;
        type = type.BaseType;
    }
    return false;
}

The call is this:

bool isQueryable = IsType(typeof(IQueryable<int>), typeof(IQueryable<>));

(Note that this will not help with basic types that implement other interfaces, since it will take a lot more code to verify this, using Type.GetInterfacesrecursively.)

+5
source

IsAssignableFrom , :

typeof(IQueryable).IsAssignableFrom(t);

IsAssignableFrom , , , IsAssignableFrom true, . , ..

+1

All Articles