Where is the caller?

  • Thread starter Thread starter Fabio Cannizzo
  • Start date Start date
F

Fabio Cannizzo

Is it possible to know who is the caller of some running method?
In ogther words, given a method of some class which is running, is there a
way, inside the method, to find out from which namespace the method was
invoked?
 
Hello

As Vijaye told you you can use stack trace, but note that if a method gets
inlined you may not get the direct caller of the method.
For example the following code will output different results in debug and
release modes because in release mode the JIT compiler will inline Method1.
So you may get that the caller of this method is Main when you expect
Method1 to be the caller.

using System;
using System.Diagnostics;
namespace ConsoleApplication2
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1 {
private static void Method1() {
Method2();
}
private static void Method2() {
StackTrace stackTrace = new StackTrace();
for(int i = 0; i < stackTrace.FrameCount; i++)
Console.WriteLine(stackTrace.GetFrame(i).GetMethod().Name);
}

[STAThread]
static void Main(string[] args) {
Method1();
}
}
}

Best regards,
Sherif
 
Back
Top