Debug and Trace in C#

.NET offers some very useful classes that allow you to monitor the workings of your program without having to constantly pop up message boxes or handle file output yourself.  Both of these classes have listener objects (the list is shared; adding a listener to Trace also adds it to Debug) which can be text files or streams you assign.

By default, the Debug class is not compiled in release mode, while the – Trace class is functional in both modes.

Some of the more useful functions and properties in these classes are described below.  These are rough descriptions and more details are available on the MSDN (links are provided).

Function Description Assert Checks for a condition. If the condition fails, it presents a message box. Flush Flushes the output buffer for the class and for all listeners. Indent Indents the output by one unit. Affects all following messages. – Unindent Removes one unit from the output. Affects all following messages. Write – WriteLine
Writes to the output panel in Visual Studio and to the trace listener objects. WriteIf – WriteLineIf
Writes only if the condition is met.


Property Description – AutoFlush Whether Flush() should be called on the listeners after every write. – IndentLevel The number of indent units currently in place. – IndentSize The number of spaces used per indent unit. Listeners The list of – TraceListener assigned to Debug and Trace.


Trace and Debug can be very powerful development tools that can help kill hard to find bugs by making them glaringly obvious. The Write and Assert functions can provide great detail as to what is happening inside your program. Your client is not running a debugger for you, but it’s easy for them to email you the error.txt file that is in thier program directory.

Write and the conditional Write function can be very useful for outputting exceptions, even the ones you are able to recover from.  It helps to find bugs that may not show up right away. Doing little things like making sure nothing added to a list is null can go a long way towards tracking down hard to find errors.

The Assert function is more useful during development than during release. Using Debug.Assert() instead of Trace.Assert() makes it easy to leave your assertions in during development, but make sure the users never have trouble with them. When something should never happen, toss an assert there to make sure. It’s amazing how often your software will try to divide by zero or convert null to a string.