Display Name
Display Name

Reputation: 15101

How to print the current executing method name via an auxiliary method?

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

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?

Upvotes: 1

Views: 421

Answers (4)

Vivek Nuna
Vivek Nuna

Reputation: 1

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

Upvotes: 2

Janne Matikainen
Janne Matikainen

Reputation: 5121

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

public static void ExecutingMethodName([CallerMemberName]string callerName= null)
{
    Console.WriteLine(callerName);
}

Upvotes: 3

Maksim Simkin
Maksim Simkin

Reputation: 9679

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);
}

Upvotes: 2

Sefe
Sefe

Reputation: 14007

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);
}

Upvotes: 3

Related Questions