Get the callerโ€™s derived class when calling the static method of the base class

I was wondering if it is possible (even through reflection et similia) to get a caller derived class inside a static method called a base class.

For example, I have a base class with a static method:

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

and derived from the class:

 public MyDerivedClass : MyBaseClass { } 

then I call:

 MyDerivedClass.MyBaseClassStaticMethod() 

Is it possible inside the MyBaseClassStaticMethod method MyBaseClassStaticMethod know which type is called by the caller?
(i.e. MyDerivedClass )

I need a line ...

+2
reflection c # derived-class
Apr 30 '13 at 14:05
source share
3 answers

No, this is impossible - in no case. static methods are not polymorphic, and therefore such information simply does not exist. Consider redesigning the code.

Update:

At compilation, the compiler replaces MyDerivedClass class that the static method is actually declared to be, in your case MyBaseClass .
So even in IL you do not see MyDerivedClass . Information exists only in your source code. This does not exist in your assembly.

+3
Apr 30 '13 at 14:08
source share
โ€” -

Generics can be used to solve your scenario as follows.

 public class BaseClass<TDerived> where TDerived : BaseClass<TDerived> { public static void LogCallerType() { Console.WriteLine(typeof(TDerived).Name); } } public class FooClass : BaseClass<FooClass> { } public class BooClass : BaseClass<BooClass> { } class Program { static void Main(string[] args) { FooClass.LogCallerType(); BooClass.LogCallerType(); } } 

This, in turn, will output the following

 1. FooClass 2. BooClass 
+3
Mar 20 '14 at 12:03
source share

First of all, the static method will not have access to the instance that calls it. The static method differs from the normal class method in that it does not have access to the 'this' link to the class instance.

If you passed 'this' as a parameter to a static method, you can try to execute it as follows. Suppose you have several derived classes that you want to test.

 public static void MyBaseClassStaticMethod(MyBaseClass callingInstance) { MyDerivedClass myDerivedClass = callingInstance as MyDerivedClass; MyDerivedClass2 myDerivedClass2 = callingInstance as MyDerivedClass2; MyDerivedClass3 myDerivedClass3 = callingInstance as MyDefivedClass3; ... // test for which derived class is calling if (myDerivedClass != null) ... else if (myDerivedClass2 != null) ... ... } 
-one
Apr 30 '13 at 14:16
source share



All Articles