How to get method name from inside that method without using reflection in C#

From C# 5 onwards you can get the compiler to fill it in for you, like this:

using System.Runtime.CompilerServices;

public static class Helpers
{
    public static string GetCallerName([CallerMemberName] string caller = null)
    {
        return caller;
    }
}

In MyMethod:

public static void MyMethod()
{
    ...
    string name = Helpers.GetCallerName(); // Now name=="MyMethod"
    ...
}

Note that you can use this wrongly by passing in a value explicitly:

string notMyName = Helpers.GetCallerName("foo"); // Now notMyName=="foo"

In C# 6, there's also nameof:

public static void MyMethod()
{
    ...
    string name = nameof(MyMethod);
    ...
}

That doesn't guarantee that you're using the same name as the method name, though - if you use nameof(SomeOtherMethod) it will have a value of "SomeOtherMethod" of course. But if you get it right, then refactor the name of MyMethod to something else, any half-decent refactoring tool will change your use of nameof as well.


As you said that you don't want to do using reflection then You can use System.Diagnostics to get method name like below:

using System.Diagnostics;

public void myMethod()
{
     StackTrace stackTrace = new StackTrace();
     // get calling method name
     string methodName = stackTrace.GetFrame(0).GetMethod().Name;
}

Note : Reflection is far faster than stack trace method.