Alex Rivera | Logout

Can you use reflection to find the name of the currently executing method?

Asked 2008-09-04T16:45:35.870
221

Like the title says: Can reflection give you the name of the currently executing method.

I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.

Update:

  • Part 2: Could this be used to look inside code for a property as well?
  • Part 3: What would the performance be like?

Final Result
I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want.

To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.

Edit
Report

2 Answers

19

Try this inside the Main method in an empty console program:

MethodBase method = MethodBase.GetCurrentMethod();
Console.WriteLine(method.Name);

Console Output:
Main

answered 2008-09-04T16:52:03.640
2

I think you should be able to get that from creating a StackTrace. Or, as @edg and @Lars Mæhlum mention, MethodBase.GetCurrentMethod()

answered 2008-09-04T16:48:10.777

Your Answer