Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 
}
like image 781
Nishantha Bulumulla Avatar asked Jun 23 '16 05:06

Nishantha Bulumulla


People also ask

How do you find the calling method?

To get name of calling method use method StackTrace. GetFrame. Create new instance of StackTrace and call method GetFrame(1). The parameter is index of method call in call stack.

How to SetValue in c#?

To use the SetValue method, first get a Type object that represents the class. From the Type, get the PropertyInfo object. From the PropertyInfo object, call the SetValue method.

What is method name in C#?

Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method.


2 Answers

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.

like image 96
Jon Skeet Avatar answered Sep 22 '22 14:09

Jon Skeet


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.

like image 31
Rahul Nikate Avatar answered Sep 18 '22 14:09

Rahul Nikate