RSS

Get Calling Method

31 Mar

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)
ect.
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;
}
Advertisements
 
Leave a comment

Posted by on March 31, 2011 in C-Sharp

 

Tags:

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: