Home > Mobile >  How can I statically acquire the type of an inheriting class from a base static method?
How can I statically acquire the type of an inheriting class from a base static method?

Time:10-06

The problem:

Given I have the following:

using System;
public class BaseClass{
        public static Type TypeOfThis => //Somehow get the type of the inheriting class?
        public static void HelloWorld() => Console.WriteLine($"Hello world, I am {TypeOfThis.Name}");
}
public class InheritingClass:BaseClass{}

How can I reference the type of the inheriting class?

GetType requires a reference, which we do not have, as we are working statically.

CodePudding user response:

The simple answer is... you can't. Normally.

Static properties are not inherited. When calling a static method from an Inheriting class, it will always call the method as if it was the parent class.

However, the workaround to this problem is Generics.

Since we need a way to tell our static property to use a certain value to determine the type during runtime, we can simply pass it on using Generics.

Modifying our code to introduce the generic will allow us to reference T, whilst defining T in our derived(Inheriting) classes.

using System;
public class BaseClass<T>{
        public static Type TypeOfThis => typeof(T);
        public static void HelloWorld() => Console.WriteLine($"Hello world, I am {TypeOfThis.Name}");
}
public class InheritingClass:BaseClass<InheritingClass>{}

The caveat is that we can no longer use our BaseClass, as we always need to define T.

  • Related