Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the calling function name from the called function [duplicate]

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

like image 281
Sauron Avatar asked Aug 21 '09 04:08

Sauron


2 Answers

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)] 
like image 77
Ben M Avatar answered Sep 24 '22 08:09

Ben M


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.

like image 25
Joe Caffeine Avatar answered Sep 26 '22 08:09

Joe Caffeine