tags:

views:

213

answers:

5

is there a way to get the instance of class that called some method?

+1  A: 

You can check the StackTrace.Get­Frame method. :)

Aggelos Mpimpoudis
+5  A: 

You can get the name of the method that calls by examining the call stack. Getting the class instance is a different story, and is not easily achieved (if even possible; I never really tried to do it). You should for instance consider the possibility that your method is called from a static method, in which case there is no class instance to find.

Either way, this is usually not a good thing to do. If the method needs access to whatever class instance that calls into it, add that as a parameter in the method.

Fredrik Mörk
A: 

Well if you are in the method, you can use this line to get the type of the class. But I'm not sure if it is really what you want since you ask for the instance.

Type yourclass = MethodBase.GetCurrentMethod().DeclaringType;
Francis B.
+2  A: 

Not really. While you can find some information on the stack, there are several situations where there is no instance, such as managed-unmanaged code boundaries (windows messages, callbacks, COM-interop etc.) or simple static methods as well.

Maybe you should explain what you are trying to achieve in the first place, so that alternative solutions can be found.

Lucero
A: 

If possible, you could try adding an

object sender

parameter as is common amongst WPF methods for example.

David