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
  • 16,276
  • 55
  • 159
  • 284
  • 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
  • 6,014
  • 5
  • 44
  • 74
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • 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
  • 76,112
  • 22
  • 180
  • 195
Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108