I know you can do
this.GetType().FullName
Edit courtesy of @Pasi Savolainen
To get
My.Current.Class
But what can I call to get
My.Current.Class.CurrentMethod
I know you can do
this.GetType().FullName
Edit courtesy of @Pasi Savolainen
To get
My.Current.Class
But what can I call to get
My.Current.Class.CurrentMethod
Check this out: http://www.codeproject.com/KB/dotnet/MethodName.aspx
StackTrace st = new StackTrace ();
StackFrame sf = st.GetFrame (0);
MethodBase currentMethodName = sf.GetMethod ();
Or, if you'd like to have a helper method:
[MethodImpl(MethodImplOptions.NoInlining)]
public string GetCurrentMethod ()
{
StackTrace st = new StackTrace ();
StackFrame sf = st.GetFrame (1);
return sf.GetMethod ();
}
Updated with credits to @stusmith.
Call System.Reflection.MethodBase.GetCurrentMethod().Name
from within the method.
You can also use MethodBase.GetCurrentMethod()
which will inhibit the JIT compiler from inlining the method where it's used.
Update:
This method contains a special enumeration StackCrawlMark
that from my understanding will specify to the JIT compiler that the current method should not be inlined.
This is my interpretation of the comment associated to that enumeration present in SSCLI. The comment follows:
// declaring a local var of this enum type and passing it by ref into a function
// that needs to do a stack crawl will both prevent inlining of the calle and
// pass an ESP point to stack crawl to
//
// Declaring these in EH clauses is illegal;
// they must declared in the main method body
Reflection has a knack for hiding the forest for the trees. You never have a problem getting the current method name accurately and quickly:
void MyMethod() {
string currentMethodName = "MyMethod";
//etc...
}
Albeit that a refactoring tool probably won't fix it automatically.
If you completely don't care about the (considerable) cost of using Reflection then this helper method should be useful:
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
//...
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetMyMethodName() {
var st = new StackTrace(new StackFrame(1));
return st.GetFrame(0).GetMethod().Name;
}