Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Answering "Which method called me?" at the run-time in .NET? Or is CallStack data readable by the code?

Presume that there are methodA() , methodB() and methodC().

And methodC() is called at the run-time.

Is is possible to know methodC() is called from what method?

I was thinking if CallStack can be read at the run-time for some checks? If yes, I think it should not be a big deal.

Any ideas?

Thanks!

like image 266
pencilCake Avatar asked Dec 18 '25 22:12

pencilCake


2 Answers

Use the StackTrace and StackFrame classes. For example:

StackTrace stackTrace = new StackTrace();          
StackFrame[] stackFrames = stackTrace.GetFrames();

foreach (StackFrame stackFrame in stackFrames)
{
    string method = stackFrame.GetMethod().Name;
    // do some stuff with method
}
like image 123
Wim Avatar answered Dec 20 '25 18:12

Wim


Yes, the call stack can be read at runtime using StackTrace.Get­Frames.

like image 39
Romain Verdier Avatar answered Dec 20 '25 18:12

Romain Verdier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!