Get Call Stack [C#]
This example shows how to get call stack in .NET. Call stack is represented by StackTrace class and a method call is represented by StackFrame class. You can get the frames using StackTrace.GetFrames method. It returns array of frames. Frame with index 0 is current executing method, frame 1 is calling method, next frame is its caller and so on.
Following example writes call stack method names. It creates an instance of StackTrace (call stack), gets all frames (method calls) and writes the method names.
[C#]using System.Diagnostics; [STAThread] public static void Main() { StackTrace stackTrace = new StackTrace(); // get call stack StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) // write call stack method names foreach (StackFrame stackFrame in stackFrames) { Console.WriteLine(stackFrame.GetMethod().Name); // write method name } }
The output is:
Main nExecuteAssembly ExecuteAssembly RunUsersAssembly ThreadStart_Context Run ThreadStart
See also
- [C#] Reflection Examples – examples how to use dynamically loaded assembly
- [C#] Get Calling Method using Reflection – how to get name of calling method
- [C#] Get Method Names using Reflection – get method names of any class
- StackTrace – MSDN – represents a call stack
- StackTrace.GetFrames – MSDN – gets all call stack frames
- StackFrame – MSDN – represents a function call on the call stack