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!
No comments:
Post a Comment