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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With