Check if a class is derived from a generic class

bernhardrusch picture bernhardrusch · Jan 19, 2009 · Viewed 154.6k times · Source

I have a generic class in my project with derived classes.

public class GenericClass<T> : GenericInterface<T>
{
}

public class Test : GenericClass<SomeType>
{
}

Is there any way to find out if a Type object is derived from GenericClass?

t.IsSubclassOf(typeof(GenericClass<>))

does not work.

Answer

JaredPar picture JaredPar · Jan 19, 2009

Try this code

static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) {
    while (toCheck != null && toCheck != typeof(object)) {
        var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
        if (generic == cur) {
            return true;
        }
        toCheck = toCheck.BaseType;
    }
    return false;
}