Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if an object inherits from an abstract generic class

I have a generic abstract class which I derive from:

abstract class SuperClass<T>
where T : SuperDataClass

abstract class SuperDataClass

The data type is limited to SuperDataClass, so every concrete data type must inherit from SuperDataClass. In the end I have pairs of SuperClass and SuperDataClass inheriters, e.g.:

class DataClassA : SuperDataClass
class ClassA : SuperClass<DataClassA>

class DataClassB : SuperDataClass
class ClassB : SuperClass<DataClassB>

How can I check if an object, e.g. ClassA inherits from SuperClass without knowing the possible data type?

I tried the following, which does not work:

if (testObject.GetType().IsAssignableFrom(typeof(SuperClass<SuperDataClass>))) {
    Console.WriteLine("The test object inherits from SuperClass");
}

So how does the if-statement needs to look like?

like image 646
sqeez3r Avatar asked Oct 21 '22 03:10

sqeez3r


1 Answers

Recursively

Type type2 = type; // type is your type, like typeof(ClassA)

while (type2 != null)
{
    if (type2.IsGenericType && 
        type2.GetGenericTypeDefinition() == typeof(SuperClass<>))
    {
        // found
    }

    type2 = type2.BaseType;
}

Note that this won't work if you are looking for an interface!

like image 170
xanatos Avatar answered Oct 27 '22 14:10

xanatos