How do you find the caller function?

Closed as an exact duplicate. How to 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'?
}
+5
source share
2 answers
Console.WriteLine(new StackFrame(1).GetMethod().Name);

However, this is not reliable, especially if optimization (for example, embedding JIT) can monkey with perceived frames of the stack.

+17
source

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 cannot work with multi-threaded ones.

+3
source

All Articles