Today, I needed to programmatically figure out what the name of the current method is. As it turns out, it’s dead simple with the help of the System.Diagnostics.StackFrame and System.Diagnostics.StackTrace classes. Here’s a simple program that illustrates the use of these classes:
`using System; using System.Diagnostics; using System.Reflection;
class App { static void WhoCalledMe() { StackTrace trace = new StackTrace(); StackFrame frame = trace.GetFrame( 1 ); MethodBase method = frame.GetMethod(); Console.WriteLine( “{0} called me”, method.Name ); }
static void Main(string[] args) { StackFrame frame = new StackFrame(); MethodBase method = frame.GetMethod(); Console.WriteLine( method.Name );
WhoCalledMe();
} }`
Notice that you can retrieve a System.Reflection.MethodBase object from the System.Diagnostics.StackFrame object. Once you have one of these puppies, the world is wide open to you ;)
Now, the performance freak in me is wondering how expensive creating a StackFrame object is …
1 archived reader comment
Jeremy (2003-12-03)
I too have been looking into obtaining the name of the current method, for tracing purposes. Having just switched from performance driven development for Unix platforms, I was also hesitant about the impact to performance.
I was concerned by the effects of either instantiating a new StackFrame for each trace message or a static one for each method. I just don’t trust that the Framework would free the resources often enough for the instantiated ones, or the unknown impact of having a static StackFrame hanging around for every method entered during an applications execution.
I initially was going to use the following Trace messages to ease cut and paste replication:
Trace.WriteLine( “ENTER - ” + new StackFrame().GetMethod().Name ); Trace.WriteLine( “EXIT - ” + new StackFrame().GetMethod().Name );
or
static StackFrame sf = new StackFrame(); Trace.WriteLine( “ENTER - ” + sf.GetMethod().Name ); Trace.WriteLine( “EXIT - ” + sf.GetMethod().Name );
which could also be done as
static string procName = new StackFrame().GetMethod().Name; Trace.WriteLine( “ENTER - ” + procName); Trace.WriteLine( “EXIT - ” + procName );
Then I discovered a Static method of the MethodBase class that will retrieve the same results without instantiating new StackFrame or other objects.
Use the static MethodBase.GetCurrentMethod() from the System.Reflection namespace to obtain a MethodBase object for the current method. The resulting Trace statements should be more efficient and will also add less clutter to the code:
Trace.WriteLine(“ENTER - ” + MethodBase.GetCurrentMethod().Name ); Trace.WriteLine(“EXIT - ” + MethodBase.GetCurrentMethod().Name );
Hope this is able to help other folks out that are trying to achieve this.