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!

pencilCake
  • 51,323
  • 85
  • 226
  • 363
  • 1
    A better question than "is it possible" is, "is it desirable". I have never seen a valid reason to do this - only invalid reasons. Please say what you're trying to accomplish. – John Saunders Dec 09 '09 at 13:47
  • 3
    John, this can be quite usefull when debugging. When you have huge code, a step by step approach isn't always the option. – David Brunelle Dec 09 '09 at 13:50
  • Actually it is curiosity. I was using one training set which you install on VS and try to accomplish the task they give you by writing a code. I was wondering how they analyze my code. How do they know one method is called from what method etc. Maybe they do it in a completely different way but it just brought up this question in my mind. – pencilCake Dec 09 '09 at 13:51
  • 1
    Duplicate of http://stackoverflow.com/questions/615940/ See this question for some more detail, especially John Leidegren's Answer – Bob Dec 09 '09 at 13:56

2 Answers2

7

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
}
Community
  • 1
  • 1
Wim
  • 11,998
  • 1
  • 34
  • 57
  • 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 Dec 09 '09 at 14:02
2

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

Romain Verdier
  • 12,833
  • 7
  • 57
  • 77