All I want to do is similar to:
public abstract class BaseClass
{
public static Type GetType()
{
return typeof(BaseClass);
}
}
But when I derive it
public class DerivedClass : BaseClass
{
}
I want to get
Assert.AreEqual(typeof(DerivedClass), DerivedClass.GetType());
How to change the BaseClass to make this assertion true?
You can't do this because your only route to a derived type from one of its bases is from an instance - and static methods don't take an instance.
I'm hoping that your example is for simplicity because otherwise re-implementing GetType() seems a bit pointless - since the
object.GetType()
will do exactly what you want.If you actually need to do this via a statically invoked method - you can't because no type information is actually available to a static method (as I say in the first paragraph).
If you actually invoking this method via an instance (but I must ask why!?) then you can do one of the following
a) Make your method an instance method on the base. It can then do
this.GetType()
(using the .Net base method) and it'll return the ultimate subtype of the instance.b) Define an extension method for
BaseClass
that does something very similar:Static methods are not inherited.
The compiler substitutes
BaseClass
forDerivedClass
when calling a base class' static methods through one of its derived classes. For example, here's the IL code for a call toDerivedClass.GetType()
: