TheDeveloperBlog.com


C# Debug Type

Debug. Problems are often difficult to diagnose. As programmers we are distant from the inner workings of our software. The Debug type, found in System.Diagnostics, provides a flexible framework for debug output.


Example. This example uses two Debug static methods. It first calls Print, which accepts parameters: a format string, and values used within that format string. And it then uses WriteLine, which prints a newline-terminated line.

Static Method
C# program that uses Debug.Print

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
	// Use Print and WriteLine.
	Debug.Print("Today: {0}", DateTime.Today);
	Debug.WriteLine("Have a nice day");
	Console.ReadLine();
    }
}

Output: in Debug window

Today: 02/05/2013 00:00:00
Have a nice day


Example 2. Next, the Debug type has a Listeners collection. We add listeners to this. Listeners are derived from the TraceListener type. They have other names, such as DelimitedListTraceListener, which writes to a file or stream.

StreamReader

Here: A DelimitedListTraceListener is created, with a target file. When Flush is called, the content is written to this file.

So: The Listeners collection gives us a way to output debug information to any target, not just a window in Visual Studio.

C# program that uses DelimitedListTraceListener

using System.Diagnostics;

class Program
{
    static void Main()
    {
	// Create trace listener.
	TraceListener listener = new DelimitedListTraceListener(@"C:\debugfile.txt");

	// Add listener.
	Debug.Listeners.Add(listener);

	// Write and flush.
	Debug.WriteLine("Welcome");
	Debug.Flush();
    }
}

Result: debugfile.txt

Welcome


Discussion. Debug.Write and Debug.WriteLine are key Debug methods. They write debug messages (by default) to the Visual Studio Debug window. With Write, no newline is appended. Multiple Write calls can be used on a single line.

Debug.Write

WriteLineIf: This is a more complex form of WriteLine. If the bool argument evaluates to true, the statement is printed.

Debug.WriteLineIf, WriteIf

Assert. If your program is not annoying enough, consider the Assert method. With Assert, if the bool evaluates to false, a dialog box is shown. This is a more emphatic (annoying) error, one less likely ignored.

Assert

With Indent, and Unindent, we can adjust the formatting of Debug output. This reduces the need for padding. We do not need to use PadLeft with Debug.WriteLine calls. Instead, we adjust indentation.

Debug.Indent, Unindent

Summary. The Debug type outputs diagnostic information. With TraceListeners, it writes to nearly any source. With expression-based methods, it writes only if a condition matches. And with assert, it makes errors forcefully known.