Reputation: 333
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<>)
Upvotes: 5
Views: 3519
Reputation: 11
@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;
}
Upvotes: 1
Reputation: 164
Found a simple way to do this: if (B.GetType().BaseType.Name == typeof(A<>).Name)
Upvotes: -1
Reputation: 144136
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;
}
}
Upvotes: 8