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.
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With