Search code examples
c#reflectionderived-class

Get Caller derived-class when calling a base-class static method


I was wondering if it's possible (even via reflection et similia) to get the caller derived-class inside of a called base-class static method.

For example, I've a base-class with a static method defined:

public MyBaseClass {
    public static void MyBaseClassStaticMethod() { /** ... **/ }
}

and a derived-from-it class:

public MyDerivedClass : MyBaseClass { }

then I call:

MyDerivedClass.MyBaseClassStaticMethod()

Is it possibile, inside of method MyBaseClassStaticMethod, to know which is the caller derived type?
(i.e. MyDerivedClass)

I just need a string...


Solution

  • No, this is not possible - by no means. static methods are not polymorphal and as such this information simply doesn't exist.
    Consider redesigning your code.

    Update:

    Upon compilation, the compiler replaces MyDerivedClass with the class the static method is actually declared on, in your case MyBaseClass.
    So even in the IL you don't see MyDerivedClass. The information exists only in your source code. It doesn't exist in your compiled assembly.