More Wonderful System.Diagnostic Goodness

One thing I missed in my eulogy to the System.Diagnostic namespace was the fact that you can capture the whole collection of stack frames. So what I hear you cry. Well if you look at the System.Exception class you see that it has a StackTrace member, but that is simply a string representation of the stack trace, it does not give you access to the actual stack frames. Well I was a bit saddened by this, and so was very happy to find out that even from an exception (that can be caught at any point in the call stack) that you can get at the full set of stack frames for the place where the exception was thrown.

Here is the code to do it - very simple as you can see, simply uses a specialized constructor of the StackTrace class.

try 
{ 
	// protected stuff here
} 
catch( Exception e ) 
{ 
	StackTrace st = new StackTrace(e); 
}

Isn't System.Diagnostics Fantastic

A student on a course I'm teaching this week asked me how to get hold of the current running method (for logging purposes). I muttered that its possible but a bit of a hack - you have to throw then catch an exception - hey presto! a stack trace.

So anyway I thought I maybe am missing something as I may be able to do what the exception framework does. Very quickly I came upon two excellent classes StackTrace and StackFrame. Well knock me down with a feather! Here was exactly what I was looking for.

By simply creating an instance of the StackFrame class using the default constructor, I can get a snapshot of the current stack frame - fanstastic! and then I can use StackFrame.GetMethod() to get the MethodInfo for the executing method.

Well maybe everyone else already knew this but it was just another example of how much stuff is in the BCL