Get derived type from static method

I guess you need something like this scenario:

void Main()
{
  Base.StaticMethod(); // should return "Base"
  Derived.StaticMethod();  // should return "Derived"
}


class Base
{
  public static void StaticMethod()
  {
    Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType.Name);
  }
}

class Derived: Base 
{
}

This code will, however, return

Base       
Base

This is due to the fact that the static method call is resolved at compile time as a call to the base class, that actually defines it, even if it was called from a derived class. The lines

Base.StaticMethod();
Derived.StaticMethod();

generates the following IL:

IL_0001:  call        Base.StaticMethod
IL_0006:  nop         
IL_0007:  call        Base.StaticMethod

In a word, it cannot be done.


Assuming you mean you have something like this

class MyBaseClass
{
    public static void DoSomething()
    {
        Console.WriteLine(/* current class name */);
    }
}

class MyDerivedClass : MyBaseClass
{
}

and want MyDerivedClass.DoSomething(); to print "MyDerivedClass", then the answer is:

There is no solution to your problem. Static methods are not inherited like instance methods. You can refer to DoSomething using MyBaseClass.DoSomething or MyDerivedClass.DoSomething, but both are compiled as calls to MyBaseClass.DoSomething. It is not possible to find out which was used in the source code to make the call.