Get the executing method name in C#


This example shows how you can get the method name for the currently executing method. Normally you don’t need to get that name (you can just look at the code you’re typing), but sometimes it’s useful for standard tracing and error handling. For example, you could make a LogState method that writes the program’s state into a log file. That method can find the executing method name automatically to put in the file.

The System.Diagnostics.StackTrace class can give you information about a program’s current state of execution. This example uses the following GetMethodName method to return the name of the method that called GetMethodName.

// Return the name of the method that called this one.
private string GetMethodName()
    return new StackTrace(1).GetFrame(0).GetMethod().Name;

This code creates a new StackTrace object. The parameter 1 passed into the constructor means the trace should start one level above the currently executing code. In other words, it should start with the method that called the GetMethodName method.

The code then calls the StackFrame object’s GetFrame method to get the first frame in the call stack. That’s the one representing the method we’re after. It uses the frame’s GetMethod routine to get information about that method, and then returns the method’s name.

The program calls GetMethodName as in the following code.

private void DoSomething()
    MessageBox.Show("In: " + GetMethodName());

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in debugging, Uncategorized and tagged , , , , , , , , , . Bookmark the permalink.