51

Possible Duplicate:
Can you use reflection to find the name of the currently executing method?
C# how to get the name of the current method from code

For example:

void foo() {
    Console.Write(__MYNAME__);
}

print: foo

it's possible do it in C#?

Community
  • 1
  • 1
Jack
  • 15,539
  • 54
  • 145
  • 264
  • In .Net 4.5, you can use CallerMemberNameAttribute to get the name of the caller. See https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx ... You can then wrap the body of your function in an anonymous function as in ([CallerMemberName] string functionName = "")=>{ }. The problems with using the reflection method as in the accepted answer are that (1) the function may be inlined, and/or (2) the function name may be obfuscated if it is non-public and the code is obfuscated. – GreatAndPowerfulOz Mar 04 '16 at 22:13

2 Answers2

110

Try this:

System.Reflection.MethodBase.GetCurrentMethod().Name 
Alex Cio
  • 5,896
  • 5
  • 41
  • 73
Raphaël Althaus
  • 58,557
  • 6
  • 89
  • 116
  • 11
    For people using .Net 4.5, there's [CallerMemberNameAttribute](https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx) – bohdan_trotsenko Mar 17 '16 at 14:34
16

You can check the stack trace

using System.Diagnostics;

// get call stack
StackTrace stackTrace = new StackTrace();

// get calling method name
Console.WriteLine(stackTrace.GetFrame(0).GetMethod().Name);

But beware, if the method is inlined you get the parent method name.

Kirk Woll
  • 73,473
  • 21
  • 178
  • 189
Albin Sunnanbo
  • 45,452
  • 8
  • 67
  • 106