Reputation: 15101
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
}
}
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
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.
Upvotes: 2
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
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
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