How to detect a subclass of a generic abstract class?

745 views Asked by At

I want to create a class hierarchy based on a generic abstract class. I need to be able to recognize my subclasses in a codebase. I tried to use Type.IsSubclassOf, but it did not work as expected.

namespace TestIsSubclassOf
{
    public class Program
    {
        private static void Main()
        {
            var testClass = typeof(TestClass);
            var isSubclass = testClass.IsSubclassOf(typeof(TestBaseClass<>)); // expected - true, actual - false
        }
    }

    public abstract class TestBaseClass<T>
    {
    }

    public class TestClass : TestBaseClass<int>
    {
    }
}

What is the correct way to recognize TestBaseClass subclass?

1

There are 1 answers

2
Twenty On BEST ANSWER

You need to check if your testClass is a subclass of TestBaseClass<int> instead of TestBaseClass<> since you could inherit from a different generic 'version' of this class.

So using the following code isSubclass returns true:

var testClass = typeof(TestClass);
var isSubclass = testClass.IsSubclassOf(typeof(TestBaseClass<int>));

If it is the case that you want to check if the class inherits TestBaseClass regardless of the used generic type you can try the following:

var testClass = typeof(TestClass);
if (testClass.BaseType.IsGenericType &&
    testClass.BaseType.GetGenericTypeDefinition() == typeof(TestBaseClass<>))
{
    //testClass inherits from TestBaseClass<>
}