40

Possible Duplicate:
How can I find the method that called the current method?

How can I get the calling function name from the called function in C#?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sauron
  • 16,668
  • 41
  • 122
  • 174
  • 1
    Duplicate of http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method – Matt Hamilton Aug 21 '09 at 05:00
  • 2
    This is a dupe, but probably worth keeping open due to the different terminology - might be helpful for people searching. – Keith Aug 21 '09 at 13:27
  • 3
    @Keith: yeah, for that reason we generally do try to keep duplicate questions around when they're asked in a significantly different way - that's why closing them automatically adds the links right at the top, so future searchers can find their way to the answers more quickly. – Shog9 Aug 21 '09 at 18:28

2 Answers2

88
new StackFrame(1, true).GetMethod().Name

Note that in release builds the compiler might inline the method being called, in which case the above code would return the caller of the caller, so to be safe you should decorate your method with:

[MethodImpl(MethodImplOptions.NoInlining)]
Ben M
  • 22,262
  • 3
  • 67
  • 71
  • 12
    Beware that walking the stack in this fashion will impose a fairly heavy performance hit. I highly recommend looking for a solution that does not involve a stack walk before making use of one. – jrista Aug 21 '09 at 05:01
  • 2
    This answer is actually better than the answers in the duplicate question because of the mention of the MethodImpl attribute. – Meta-Knight Aug 29 '09 at 16:35
  • 9
    I know this is a dupe and tagged .net 3.5, but to help the searchers that stumble on this one first (like me), it would be good to indicate in your answer that in C# 5.0 you can now use caller Information as described in: http://visualstudiomagazine.com/articles/2012/11/01/more-than-just-async.aspx – acarlon Sep 13 '13 at 02:46
  • @acarlon Thanks for the link! Didn't even realize those attributes existed. – AridTag Sep 26 '13 at 16:13
  • It will be faster if `fNeedFileInfo` is `false` instead of `true` (second parameter for `StackFrame constructor`, just tried it with batches of thousands of calls). – ygoe Aug 19 '16 at 06:58
18

This will get you the name of the method you are in:

string currentMethod = System.Reflection.MethodBase.GetCurrentMethod().Name;

Use with caution since there could be a performance hit.

To get callers:
StackTrace trace = new StackTrace();
int caller = 1;

StackFrame frame = trace.GetFrame(caller);

string callerName = frame.GetMethod().Name;

This uses a stack walk to get the method name. The value of caller is how far up the call stack to go. Be careful not to go to far.

Joe Caffeine
  • 868
  • 5
  • 10