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'?
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With