Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the name of the method in C#

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?

like image 290
patachi Avatar asked Nov 29 '22 08:11

patachi


2 Answers

.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.

like image 28
p.s.w.g Avatar answered Dec 12 '22 23:12

p.s.w.g


This will get you name -

string methodName = System.Reflection.MethodInfo.GetCurrentMethod().Name;

OR

string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
like image 132
Rohit Vats Avatar answered Dec 13 '22 00:12

Rohit Vats