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.
}
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] 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.
See more on this question at Stackoverflow