Get derived class type from a base’s class static method

This can be accomplished easily using the curiously recurring template pattern

class BaseClass<T>
    where T : BaseClass<T>
{
    static void SomeMethod() {
        var t = typeof(T);  // gets type of derived class
    }
}

class DerivedClass : BaseClass<DerivedClass> {}

call the method:

DerivedClass.SomeMethod();

This solution adds a small amount of boilerplate overhead because you have to template the base class with the derived class.

It’s also restrictive if your inheritance tree has more than two levels. In this case, you will have to choose whether to pass through the template argument or impose the current type on its children with respect to calls to your static method.

And by templates I, of course, mean generics.

Leave a Comment