2

I am aiming to add some #if DEBUG to my methods however I don't want to edit the code I copy and Paste into each method.

Is there a generic piece of code like this:

void DoSomething()
            {
#if Debug
            Log("Now In " + MethodName);
#endif
            }

Where MethodName is populated to equal DoSomething, or whichever Method called the Log?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Dave Gordon
  • 1,815
  • 4
  • 30
  • 52
  • 2
    possible duplicate of [Can you use reflection to find the name of the currently executing method?](http://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method) – Yurii Feb 01 '14 at 12:28

2 Answers2

10

If you're using .NET 4.5 you can use the CallerMemberName attribute:

public static GetCallerMemberName([CallerMemberName]string caller = null)
{
    return caller;
}

Note that when calling this method you don't need to pass anything as an argument - the C# compiler does the work for you. This also means that you avoid performing reflection at runtime, which makes this method much faster.

Usage:

void DoSomething()
{
#if Debug
    Log("Now In " + GetCallerMemberName()); // Logs "Now in DoSomething"
#endif
}
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
7
System.Reflection.MethodBase.GetCurrentMethod().Name
Ant P
  • 24,820
  • 5
  • 68
  • 105