Oct 10 2007

Debugging with Debug.WriteLine And StackTrace

Published by at 3:20 pm under General

I’m not sure if this is a well known feature of Visual Studio but it’s something I’ve used in the past and have just had need to use again.  When debugging an application in Visual Studio it is possible to use System.Diagnostics.Debug.WriteLine() or System.Diagnostics.Trace.WriteLine() to write messages to the output window in Visual Studio, I’m sure that’s nothing new to most .Net developers.

What you might not be aware of is the fact that if you output the full path to a file, you can then double click on the file name in the output window and it will be opened in Visual Studio.  Also, if you output a number in parentheses after the file name, Visual Studio will try to take you to that line number, e.g.:

C:\My Solution\Shared\ClientForms\Forms\frmRates.vb(547)

That’s great, but how could you use this IRL? I’ve just combined this with the System.Diagnostics.StackTrace class.  I have a method that gets called many times from many different locations in the code and, under certain circumstances, I’d like to know where the method is being called from.  You can use the StackTrace class to find out where the method is being called from, and the Debug.WriteLine() to output this information to the output window:

 1: StackTrace myStack = new StackTrace(true); 
 2: StackFrame lastFrame = myStack.GetFrame(1); 
 3: Debug.WriteLine(string.Format("{0}({1})", 
 4:                               lastFrame.GetFileName,
 5:                               lastFrame.GetFileLineNumber));

Normally if you are wanting to break out to the source code when you hit the line would probably put a break point, possibly with a condition, but sometimes you might not want to break execution and instead just want to record the fact that you hit that point and how you got to it, in which case this snippet could be useful.

kick it on DotNetKicks.com

4 responses so far