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#?

3
  • 1
    Duplicate of stackoverflow.com/questions/171970/… Aug 21, 2009 at 5: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, 2009 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, 2009 at 18:28

2 Answers 2

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)]
5
  • 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, 2009 at 5:01
  • 2
    This answer is actually better than the answers in the duplicate question because of the mention of the MethodImpl attribute. Aug 29, 2009 at 16:35
  • 10
    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: visualstudiomagazine.com/articles/2012/11/01/…
    – acarlon
    Sep 13, 2013 at 2:46
  • @acarlon Thanks for the link! Didn't even realize those attributes existed.
    – AridTag
    Sep 26, 2013 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, 2016 at 6: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.

2
  • 1
    I need which method calls the current method.
    – Sauron
    Aug 21, 2009 at 5:11
  • The way you get the caller's name from the stack trace, will it be a performance hit?
    – Panos
    Oct 29, 2014 at 13:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.