Friday, February 7, 2014

Method to get the name of a calling method in C#

When doing quick testing with debug logging it's usually helpful to include the name of the method where a log call originates.  It's pretty easy to include, but it can be a hassle if it's a large method you have to scroll through to find the name, or God forbid if the method name changes in the future.  What would be handy is a quick and easy way to get the name of a calling method at runtime so it's guaranteed to be the correct name.

This is one thing I've wanted for quite some time, and for one reason or another I never spent the time to investigate how to access this until now.  It was surprisingly easy to setup and works very nicely by taking advantage of the System.Diagnostics.StackFrame class to determine the calling method.

Here's what I came up with.  You're welcome to copy and use this code in your own projects.

1:  // Use a stack frame to get the name of the method which called this method   
2:  public static string GetCallingMethodName ( bool includeClassName = true )  
3:  {  
4:      System.Diagnostics.StackFrame lastFrame = new System.Diagnostics.StackFrame(1);  
5:    
6:      // return ClassName.MethodName  
7:      if ( includeClassName == true )  
8:          return lastFrame.GetMethod().DeclaringType.Name + "." + lastFrame.GetMethod().Name;  
9:    
10:      // return just MethodName  
11:      return lastFrame.GetMethod().Name;  
12:  }  

I'm not sure what the performance penalty is for using this at a high frequency, so if anyone has insight into that I would love to hear it!

1 comment: