3

Possible Duplicate:
How can I find the method that called the current method?

Hi, how can i determine the caller of a method from within the method? Eg:

SomeNamespace.SomeClass.SomeMethod() {
   OtherClass();
}

OtherClass() {
   // Here I would like to able to know that the caller is SomeNamespace.SomeClass.SomeMethod
}

Thanks

Community
  • 1
  • 1
pistacchio
  • 56,889
  • 107
  • 278
  • 420
  • 4
    Dupe - http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method and http://stackoverflow.com/questions/280413/c-how-do-you-find-the-caller-function-closed – William Jul 22 '09 at 06:47

3 Answers3

6

These articles should be of help:

  1. http://iridescence.no/post/GettingtheCurrentStackTrace.aspx
  2. http://blogs.msdn.com/jmstall/archive/2005/03/20/399287.aspx

Basically the code looks like this:

StackFrame frame = new StackFrame(1);
MethodBase method = frame.GetMethod();
message = String.Format("{0}.{1} : {2}",
method.DeclaringType.FullName, method.Name, message);
Console.WriteLine(message);
Bogdan Maxim
  • 5,866
  • 3
  • 23
  • 34
  • 5
    Do be careful. I was caught by this bug once. If you build your application for release, the method can get in-lined and your stack trace will look different. – Anish Jan 09 '13 at 18:23
1

You need to use the StackTrace class

Snippet from the MSDN

// skip the current frame, load source information if available 
StackTrace st = new StackTrace(new StackFrame(1, true)) 
Console.WriteLine(" Stack trace built with next level frame: {0}",
  st.ToString());
Shay Erlichmen
  • 31,691
  • 7
  • 68
  • 87
1

You can use the System.Diagnostics.StackTrace class:

  StackTrace stackTrace = new StackTrace();           // get call stack
  StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

  // write call stack method names
  foreach (StackFrame stackFrame in stackFrames)
  {
    Console.WriteLine(stackFrame.GetMethod().Name);   // write method name
  }
M4N
  • 94,805
  • 45
  • 217
  • 260