StackTrace and StackFrame
All of us would be aware of the Call Stack, which we usually inspect while debugging any type of application. It would be great if we could really inspect the Call Stack in some way in our code at runtime. System.Diagnostics namespace gives you just that in the form of two very useful classes : The StackFrame and the StackTrace.
A Stack frame is created when a method call is made. Typically, the stack frame contains the information related to the method call and this can be inspected by calling the GetMethod method of a StackFrame instance. This method just returns an instance of type MethodBase. Also, for debug builds, you can get information like source file name, line number etc.
StackTrace is nothing but a collection of StackFrame instances that are on the stack. One place where you would have used this is the StackTrace of the exception object which is just a string representation of the StackTrace. Infact, you can create a Stacktrace instance out of an exception object.
Here's a simple usage which just prints out the call stack till the current method:
StackTrace st = new StackTrace();
for(int i = 0; i < st.FrameCount ; i ++)
{
Console.WriteLine(st.GetFrame(i).GetMethod().Name );
}
There is one small catch. As you all know, as a way of runtime optimization, the CLR may decide to inline a method call. In such cases, you will not have a Stack Frame created (there is no method call at all here).
I can think of few uses of Stacktrace: (There may be many more..)
1. Inspect the metadata of the caller of your method, maybe for security purposes.
2. Check the depth of a method call. This can be useful when the method call is recursive.
3. Log call patterns at runtime for analysis purposes.