Search code examples
c#introspection

How to get the name of the current method from code


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.