Tadeusz
Tadeusz

Reputation: 6883

How to know object from which method is called?

I have a static class, which methods is called from instances of another class. How I can to know which instance has called method without some adding method parameters?

Example:

static class SomeStaticClass
{
 public static void SomeGreatMethod (/*NO PARAMETERS*/)
 {
   LittleClass caller = //How to obtain caller instance here?
 }
}

class LittleClass
{
 public void SomeMethod ()
 {
   //some code
   SomeStaticClass.SomeGreatMethod (/*NO PARAMETERS*/);
 }
}

Upvotes: 0

Views: 141

Answers (4)

Tigran
Tigran

Reputation: 62256

Sometimes I use this

private static Type GetCallingMethodHolderType()
{
   const int iCallDeepness = 0; //can vary this ...
   System.Diagnostics.StackTrace stack = new System.Diagnostics.StackTrace(false);
   System.Diagnostics.StackFrame sframe = stack.GetFrame(iCallDeepness);
   return sframe.GetMethod().ReflectedType; //This will return a TYPE which holds the method.
}

EDIT

I edited the post in order to return the TYPE of the object wich holds the caller method. Instance, like you requested, imo, it's not possible to get.

Should work for you.

Upvotes: 0

undefined
undefined

Reputation: 34248

Take a look here, you need to use the callstack

http://www.csharp-examples.net/reflection-calling-method-name/

Upvotes: 0

Novakov
Novakov

Reputation: 3095

You can get a StackFrame and read from it entire stack trace

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500645

You can potentially find out which class contains the calling method by creating a stack trace - although inlining can mess this up.

You can't find out which instance is making the call unless you're using the debugging API.

If you need to do either of these things, you've probably got a design problem. There are some areas of the framework which do something similar to impose security, but that's a pretty rare case. Normally, if you need that information in SomeGreatMethod, you should simply provide it as part of the call - or make it an instance method in a non-static class, and provide the appropriate contextual information on construction.

Upvotes: 2

Related Questions