2

Is there a way to programatically get the name of which method or property the current code is executing under?

void Test() { MessageBox.Show("This is a message from " + GetNameOfCurrentMethod); }

I thought about throwing an exception, catching it and parsing the stack trace but there should be a better way to do this.

Raheel Khan
  • 14,205
  • 13
  • 80
  • 168
  • http://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method – Rawling Apr 17 '12 at 11:58
  • Duplicate of http://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method – Chris Gessler Apr 17 '12 at 11:59

4 Answers4

4

Try:

MethodInfo.GetCurrentMethod().Name
Tudor
  • 61,523
  • 12
  • 102
  • 142
2
System.Reflection.MethodBase.GetCurrentMethod().Name;
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
1

Have you searched? C# how to get the name of the current method from code

Community
  • 1
  • 1
Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42
0

Not currently relevant but for future readers .NET 4.5 introduces a CallerMemberNameAttribute which can be applied to optional method parameters to get the caller information (providing it doesn't get removed from Beta to RTM!). http://msdn.microsoft.com/en-us/library/hh534540(v=vs.110).aspx

Dave S
  • 775
  • 5
  • 7