0

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?

Hozuki Ferrari
  • 305
  • 3
  • 11

1 Answers1

1

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<>
}
Twenty
  • 5,234
  • 4
  • 32
  • 67