Thursday, 10 April 2008

How to access the Call Stack C#

As methods are called, information about them are placed on the call stack. The call stack is invaluable in development work for debugging problems, but it can also be useful in other situations (e.g. when logging for an entire app or library is processed by a logging utility in one location).

.NET makes it simple for us to work with the call stack. The functionality is provided via the System.Diagnostics.StackTrace, System.Diagnostics.StackFrame and System.Reflection.MethodBase classes.

Access the call stack via a new instance of the StackTrace class. The stack contains stack frames, these frames represent each method executing on the current thread; programmatically access a frame via a StackFrame instance. Using the StackFrame.GetMethod(), which returns a MethodBase object, you can now easily retrieve the detailed information you wanted. The sample code below demonstrates this.

// First create an instance of the call stack
StackTrace callStack = new StackTrace();

// Next select the frame we want...
// 0 : current frame for the current method
// 1 : Frame that called the current method
// 2 : Frame that called the frame that called the current method
// 3 : ...you get the idea!
StackFrame frame = callStack.GetFrame(1);

// Using StackFrame.GetMethod(), which returns a 
// MethodBase object, we can obtain detailed 
// information about about a method
MethodBase method = frame.GetMethod();

// Get the declaring type and method names 
string declaringType = method.DeclaringType.Name;
string methodName = method.Name;

2 comments:

Andrew said...
This comment has been removed by the author.
Andrew said...

Thank you very much, I found your article extremely useful. Saved me a lot of time and effort :D

I would also like to add that declaring the StackFrame with the following parameters would allow you to skip the method you're accessing the stack from and allow you to get the line number information:

StackTrace callStack = new StackFrame(1, true);