teshio
teshio

Reputation:

How to get the class name of a derived class when executing a static method in the base class?

In the following I would like a call to MyOtherClass.MyStaticMethod() to output "MyOtherClass", is this possible? All my current attempts give me "MyClass".

The issue I have is that I can't easily change MyOtherClass, since there are 100s of classes which extend from MyClass.

public class MyClass
{
    public static string MyStaticMethod()
    {
        string className = typeof(MyClass).Name;
        Console.WriteLine(className);
    }
}
public class MyOtherClass : MyClass{ }

Upvotes: 1

Views: 2735

Answers (4)

AxelEckenberger
AxelEckenberger

Reputation: 16936

Starting from version 3.5 of the .NET framework you could use an extension function to retrieve the information about the instance of the class.

public static class MyClassExtensions {
  public static string Name(this MyClass instance) {
    return typeof(instance).Name;
  }
}

Provides an instance method without modifying the definition of MyOtherClass.

Upvotes: 0

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48156

This is somewhat related to a question I just asked last week: C# static member “inheritance” - why does this exist at all?.

To cut to the chase, C# doesn't really support static method inheritance - so, you can't do what you ask. Unfortunately, it is possible to write MyOtherClass.MyStaticMethod() - but that doesn't mean there's any real inheritance going on: under the covers this is just the scoping rules being very lenient.

Edit: Although you can't do this directly, you can do what C++ programmers call a Curiously Recurring Template Pattern and get pretty close with generics[1]:

public class MyClass<TDerived> where TDerived:MyClass<TDerived> {
    public static string MyStaticMethod() { return  typeof(TDerived).Name; }
}
public class MyOtherClass : MyClass<MyOtherClass> { }
public class HmmClass:MyOtherClass { }

void Main() {
    MyOtherClass.MyStaticMethod().Dump(); //linqpad says MyOtherClass
    HmmClass.MyStaticMethod().Dump();  //linqpad also says MyOtherClass
}

Here, you do need to update the subclass - but only in a minor fashion.

Upvotes: 1

ewernli
ewernli

Reputation: 38625

In C# and Java you can overload a static method, but not override it. That is, polymorphism and inheritance on static method does not exists. (See this question for more detail)

There is not concept of this on static method, and as a consequence, you can not get the type in a polymorphic way. Which means that you would need to define one static method per class in a way to print the right type.

Upvotes: 1

Paul Manzotti
Paul Manzotti

Reputation: 5147

Don't you need it to be an instance method, then call

string className = typeof(this).Name;

Upvotes: 1

Related Questions