Question

In following scenario:

public class A<T> { }

public class B : A<AClass> { }

Is is possible to determine if B is a subclass of A without specifying AClass (the generic parameter)? As in:

typeof(B).IsSubclassOf(A<>)
Was it helpful?

Solution

Yes but you'll have to go through the hierarchy yourself:

var instance = new B();
Type t = instance.GetType();

bool isA = false;
while(t != typeof(object))
{
    if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(A<>))
    {
        isA = true;
        break;
    }
    else
    {
        t = t.BaseType;
    }
}

OTHER TIPS

@Lee answer is good for search in whole full base class hierarchy.

If someone need to determine if subclass inherits from single generic subclass A<T>

Type t = typeof(B);
bool isSubClass = t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefination() == typeof(A<>);

Extension method can be used:

public static bool IsSubClassOfEx(Type t, Type baseType)
{
  return t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == baseType;
}

Found a simple way to do this: if (B.GetType().BaseType.Name == typeof(A<>).Name)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top