HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How to get the name of the current method from code

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfromnamethecurrentmethodcodeget

Problem

I know you can do

this.GetType().FullName


To get

My.Current.Class


But what can I call to get

My.Current.Class.CurrentMethod

Solution

using System.Diagnostics;
...

var st = new StackTrace();
var sf = st.GetFrame(0);

var currentMethodName = sf.GetMethod();


Or, if you'd like to have a helper method:

[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentMethod()
{
    var st = new StackTrace();
    var sf = st.GetFrame(1);

    return sf.GetMethod().Name;
}


Updated with credits to @stusmith.

Code Snippets

using System.Diagnostics;
...

var st = new StackTrace();
var sf = st.GetFrame(0);

var currentMethodName = sf.GetMethod();
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentMethod()
{
    var st = new StackTrace();
    var sf = st.GetFrame(1);

    return sf.GetMethod().Name;
}

Context

Stack Overflow Q#2652460, score: 450

Revisions (0)

No revisions yet.