1

ExecutingMethodName is intended to print the method name of the caller. For example:

  • static void Main(string[] args){Auxiliary.ExecutingMethodName();} should print Main.

  • static void Foo(){Auxiliary.ExecutingMethodName();} should print Foo.

static class Auxiliary
{
    public static void ExecutingMethodName()
    {
        Console.WriteLine(new StackFrame(0).GetMethod().Name);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Auxiliary.ExecutingMethodName();// should print Main
    }
    static void Foo()
    {
        Auxiliary.ExecutingMethodName();// should print Foo
    }    
}

Question

The current implementation above always print ExecutingMethodName that is not what I want. How to print the current executing method name via an auxiliary method?

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165

4 Answers4

3

You have to skip the first entry in the stack frame (which belongs to ExecutingMethodName):

public static void ExecutingMethodName()
{
    Console.WriteLine(new StackFrame(1).GetMethod().Name);
}
Sefe
  • 13,731
  • 5
  • 42
  • 55
3

Use the CallerMemberNameAttribute instead using something from the stackframe. Much cleaner way.

public static void ExecutingMethodName([CallerMemberName]string callerName= null)
{
    Console.WriteLine(callerName);
}
Janne Matikainen
  • 5,061
  • 15
  • 21
  • Voted up. Nice idea. What is the purpose of initializing `callerName=null`? – Second Person Shooter Jan 24 '17 at 13:33
  • 1
    "You apply the CallerMemberName attribute to an optional parameter that has a default value. You must specify an explicit default value for the optional parameter. You can't apply this attribute to parameters that aren't specified as optional." from the MSDN link provided. – Janne Matikainen Jan 24 '17 at 13:37
2

Just change 0 to 1 in stackframe call in your method (StackFrame(0) is your currrent position in call stack and you need to go one step back):

public static void ExecutingMethodName()
{
    Console.WriteLine(new StackFrame(1).GetMethod().Name);
}
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
2

Use the below code. You have to use StackFrame(1), StackFrame(2) will always be the ExecutingMethodName, actually you have to print the caller of ExecutingMethodName.

public static void ExecutingMethodName()
        {
            Console.WriteLine(new StackFrame(1).GetMethod().Name);
        }

You can refer StackFrame Constructor (Int32)

In C# 5 it has become more easy.

CallerMemberNameAttribute

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197