Is there any way to get the name of the method that currently we are in it?
private void myMethod()
{
string methodName = __CurrentMethodName__;
MessageBox(methodName);
}
Like this.ToString() that returns the class name is there any possible way to get name of the method by something like monitoring or tracing the app?
.NET 4.5 adds Caller Information attributes so you can use the CallerMemberNameAttribute
:
using System.Runtime.CompilerServices;
void myMethod()
{
ShowMethodName();
}
void ShowMethodName([CallerMemberName]string methodName = "")
{
MessageBox(methodName);
}
This has the benefit of baking in the method name at compile time, rather than run time. Unfortunately there's no way to prevent someone calling ShowMethodName("Not a real Method")
, but that may not be necessary.
This will get you name -
string methodName = System.Reflection.MethodInfo.GetCurrentMethod().Name;
OR
string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
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