views:

45

answers:

2

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!

+5  A: 

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
  }
Wim Hollebrandse
just be aware this is an expensive function that you probably only want to do in exception(al) circumstances. Hard to imagine what you'd want to do that isn't already part of StackTrace in an Exception-derived class. If you're thinking of logging, you'll have to ask yourself if the overhead is worth it.
No Refunds No Returns
+1  A: 

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

Romain Verdier