Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find the caller function? [duplicate]

Closed as exact duplicate of "How can I find the method that called the current method?"

Is this possible with c#?

void main()
{
   Hello();
}

void Hello()
{
  // how do you find out the caller is function 'main'?
}
like image 784
Serhat Ozgel Avatar asked Nov 11 '08 09:11

Serhat Ozgel


People also ask

What is the caller of the function?

A caller is a function that calls another function; a callee is a function that was called. The currently-executing function is a callee, but not a caller.

How do you find out the caller function in JavaScript?

To find out the caller function, name a non-standard the function. caller property in JavaScript. The Function object is replaced by the name of the function of which you need to find out the parent function name. If the function Welcome was invoked by the top-level code, the value of Welcome.


2 Answers

Console.WriteLine(new StackFrame(1).GetMethod().Name);

However, this is not robust, especially as optimisations (such as JIT inlining) can monkey with the perceived stack frames.

like image 107
Marc Gravell Avatar answered Oct 11 '22 23:10

Marc Gravell


From here:

System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1);
System.Diagnostics.StackFrame sf = st.GetFrame(0);
string msg = sf.GetMethod().DeclaringType.FullName + "." +
sf.GetMethod().Name;
MessageBox.Show( msg );

But there is also a remark that this could not work with multi-threading.

like image 45
schnaader Avatar answered Oct 11 '22 22:10

schnaader