How to get the name of the current method from code [duplicate]

Solution 1:

Call System.Reflection.MethodBase.GetCurrentMethod().Name from within the method.

Solution 2:

using System.Diagnostics;
...

var st = new StackTrace();
var sf = st.GetFrame(0);

var currentMethodName = sf.GetMethod();

Or, if you'd like to have a helper method:

[MethodImpl(MethodImplOptions.NoInlining)]
public string GetCurrentMethod()
{
    var st = new StackTrace();
    var sf = st.GetFrame(1);

    return sf.GetMethod().Name;
}

Updated with credits to @stusmith.

Solution 3:

Since C# version 6 you can simply call:

string currentMethodName = nameof(MyMethod);

In C# version 5 and .NET 4.5 you can use the [CallerMemberName] attribute to have the compiler auto-generate the name of the calling method in a string argument. Other useful attributes are [CallerFilePath] to have the compiler generate the source code file path and [CallerLineNumber] to get the line number in the source code file for the statement that made the call.


Before that there were still some more convoluted ways of getting the method name, but much simpler:

void MyMethod() {
  string currentMethodName = "MyMethod";
  //etc...
}

Albeit that a refactoring probably won't fix it automatically.

If you completely don't care about the (considerable) cost of using Reflection then this helper method should be useful:

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
//...

[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetMyMethodName() {
  var st = new StackTrace(new StackFrame(1));
  return st.GetFrame(0).GetMethod().Name;
}