Small Tip: Getting the name of the current or calling method at runtime for debugging

Here's a simple little trick that you can use when using Debug Mode(though it does have its overhead, so turn it off when you don't need it). You know how you write those nasty trace messages that say "I'm entering/leaving this current method"? Ain't it a nasty thing to keep writing the names by hand, or using Macros to automate it? The maintenance is just too much when refactoring method names.
 
You can use the class "StackTrace" located under "System.Diagnostics" to return the name of the current method (or one of it's callers up the stack. So, if you wanted to write the name of the current method with StackTrace you could write:
 
   Debug.WriteLine("Entering " + new StackTrace().GetFrame(0).GetMethod().Name);
 
The "0" indicated the index of the frame to show, in this case, the lowest one in the stack - the current one. "1" means the immediate caller to this method, "2" means the caller to the caller and so on. You need to watch out if you use this in Release mode, because the compiler may have some interesting optimization effects, like removing redundant method calls etc.. but it's a nice technique for tracing.
 
 
There's even a simpler way to do this by calling the MethodBase class's static "GetCurrentMethod" method:
 
   Debug.WriteLine("Entering " + MethodBase.GetCurrentMethod().Name);
 
But using the first method gets you the ability to look *up* the stack so you can write code like this:
 
private void MyMethod()
{
 Debug.WriteLine("Entering " + My.Name);
}
 
public class My       
{
   public static string Name
        {
            get
            {
                try
                {
                    return new StackTrace().GetFrame(1).GetMethod().Name;
                }
                catch (Exception)
                {
 
                    return "Unknown Method";
                }
            }
}
 
You can go further by adding other stuff to the current method like a special description attribute shown in debug mode like this:
 
[Desc("This method is just silly")]
public void MyMethod()
{
   Debug.WriteLine(My.Description);
}

this is possible by adding the following property to the "My" class"
 
    public static string Description
        {
            get
            {
                try
                {
                    return new StackTrace().GetFrame(1).GetMethod()
                        .GetCustomAttributes(typeof(Desc),true)[0].Description;
                }
                catch (Exception)
                {
 
                    return string.Emtpy;
                }
            }
        }
Published Monday, May 15, 2006 1:05 AM by RoyOsherove
Filed under: ,

Comments

Sunday, May 14, 2006 7:26 PM by Wallym

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Nice info. Thanks Roy!
Monday, May 15, 2006 1:48 AM by Mihir Solanki

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Excellent ...
Monday, May 15, 2006 2:45 AM by Hermann Klinke

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

You could also just use MethodBase.GetCurrentMethod(). This returns the MethodInfo of the currently executing method. Both classes are in the System.Reflection namespace.
Monday, May 15, 2006 2:46 AM by Hermann Klinke

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Ooops. Sorry, I did not read your post entirely ;-). You can delete my comment.
Monday, May 15, 2006 1:30 PM by Imran Koradia

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Any sort of overhead that one should be concerned about when using either of these techniques (StackTrace or MethodBase) considering that the tracing code would actually be part of the production code? Both the techniques are indeed very useful to log trace statements but when we're speaking of thousands of users, would the method calls have any effect on performance whatsoever (compared to just sticking in string constants)?

Thanks!
Monday, May 15, 2006 1:44 PM by Roy Osherove

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

Imran. There is a perf impact compared to strings, but I wouldn't count this out before I did some perf testing. Try adding some of that code to your real application and *measure*.
I'm not a big fan of premature optimization, and I only optimize for speed when I find out that I need to.
So - Id run tests with and without this code and check the perf difference.
Most likely it will be negligible. If it doesn't - You can always use hard coded string in the places where the perf hit is the biggest and use the easier method listed here for places with less overhead.
Tuesday, May 16, 2006 9:54 AM by David M. Kean

# re: Small Tip: Getting the name of the current or calling method at runtime for debugging

You probably don't want to catch Exception, if the JIT fails to JIT a method, or if an assembly is missing or a attribute's constructors throws an exception you are going to catch and handle these exactly the same; by ignoring them. Not real good practice.