Tag Archives: Calling method

Get Calling Method

Have you ever asked yourself that it could be useful to find out the method that has called the current method that is executed?
No? Me neither, but I heard that question. If you would ask the same question I will answer it for you.

You can do this by using the StackStrace Object. There you have the GetFrames Method, that returns all method information inclusive all constructors up to the main method and farther.
The return value of the GetFrames() method is an array of StackFrame. This array contains for each calling method a separate StackFrame Object. From that StackFrame object you can call the GetMethod() method to get the MethodBase object on wich you can get the Name, Namespace ect.

But the question in the beginnin was “How to get the calling method”. Whell, none easier than that. The StackFrame array is ordered in following way:
Position 0: Actual method (m1)
Position 1: Caller of method m1 (m2)
Position 2: Caller of method m2 (m3)
Hence that you can easily assume that the StackFrame object on position 1 contains the information about the calling method.

public void Test()
  StackTrace stackTrace = new StackTrace();
  StackFrame[] stackFrames = stackTrace.GetFrames();
  MethodBase mb = stackFrames[1].GetMethod();  //this is the calling method of Test()
  String methodName = mb.Name;
Leave a comment

Posted by on March 31, 2011 in C-Sharp