Nishantha Bulumulla
Nishantha Bulumulla

Reputation: 429

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

I want get the method name from inside itself. This can be done using reflection as shown below. But, I want to get that without using reflection

System.Reflection.MethodBase.GetCurrentMethod().Name 

Sample code

public void myMethod()
{
    string methodName =  // I want to get "myMethod" to here without using reflection. 
}

Upvotes: 14

Views: 8785

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499760

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.

Upvotes: 40

Rahul Nikate
Rahul Nikate

Reputation: 6337

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.

Upvotes: 5

Related Questions