Follow @RoyOsherove on Twitter

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;
                }
            }
        }

Trend: Who works the hardest and knows the least?

Why did 2,000 people leave during Steve Sinoflsky's Tech-Ed Talk? Not Just Boredom