HomeSearch

C# Debug.Write Examples

Use Debug.Write from System.Diagnostics. Review other methods like WriteLine and Assert.
Debug.Write. This method is found in System.Diagnostics. It prints a message to the Visual Studio console. It is permanent—it is disabled when Debug is disabled in the program.
Notes, Debug. We do not need to remove Debug class calls to improve performance. Other methods in the Debug class, like WriteLineIf, are also covered here.
Debug.WriteLine example. The .NET Framework has a Debug static class in System.Diagnostics. Here we see the Write and WriteLine methods, which may be the most useful overall.

Write: This writes text to the Output window, but does not append a newline to the text.

And: The WriteLine method writes a text line to the "Output" console in Visual Studio.

Output: In Visual Studio, you have an "Output" window. Go to View -> Output, and then you will see Output appear.

C# program that uses Debug.WriteLine using System.Diagnostics; static class Program { static void Main() { Debug.Write("A"); Debug.Write("B"); Debug.Write("C"); Debug.Write(" "); Debug.WriteLine("Message is written"); } } Output It will write "ABC Message is written" to the Output window.
Listeners. Next, the Debug type has a Listeners collection. We add listeners to this. Listeners are derived from the TraceListener type.

Tip: Listeners 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
Indent. The Debug type provides the Indent and Unindent methods. These adjust the left-hand margin on the output. This program invokes Debug.Indent.

Unindent: At the end, we call Debug.Unindent. This means the middle two calls to Debug.WriteLine have an indent level (IndentLevel) of 1.

Note: Debug.IndentLevel is a property. Instead of using Indent and Unindent, you can assign to IndentLevel. This is sometimes clearer.

C# program that uses Indent and Unindent using System.Diagnostics; class Program { static void Main() { // 1. Debug.WriteLine("One"); // Indent and then unindent after writing. Debug.Indent(); Debug.WriteLine("Two"); Debug.WriteLine("Three"); Debug.Unindent(); // End. Debug.WriteLine("Four"); // Sleep. System.Threading.Thread.Sleep(10000); } } Output One Two Three Four
IndentSize. This is the number of spaces an indent has. The program changes IndentSize to 2, and then directly sets IndentLevel to 1. This results in an indent of 2 spaces one time.

Tip: The total number of spaces that a Debug line will be indented is equal to the product of IndentSize and IndentLevel.

Tip 2: The Debug.Indent, Unindent, IndentSize and IndentLevel members simplify debug output.

C# program that uses IndentSize using System.Diagnostics; class Program { static void Main() { // Write IndentSize. Debug.WriteLine(Debug.IndentSize); // Change IndentSize. Debug.IndentSize = 2; Debug.IndentLevel = 1; Debug.WriteLine("Perls"); // Sleep. System.Threading.Thread.Sleep(10000); } } Output 4 Perls
WriteLineIf example. Debug.WriteLineIf prints output only if a condition is met. Here we demonstrate how Debug.WriteLineIf and Debug.WriteIf can be used.

Bool: Debug.WriteLineIf and Debug.WriteIf have a first argument of bool type. This can be any expression that evaluates to true or false.

Bool

Here: We print Thursday if IsThursday() evaluates to true. We use a bool field and an expression that is evaluated at runtime.

True, False

Debug: Debug methods are only executed if the program is run in DEBUG mode. This is because they use conditional compilation attributes.

Conditional
C# program that demonstrates WriteLineIf using System; using System.Diagnostics; class Program { static void Main() { Debug.WriteLineIf(IsThursday(), "Thursday"); Debug.WriteLineIf(_flag, "Flag"); Debug.WriteLineIf(int.Parse("1") == 1, "One"); Debug.WriteIf(true, "True"); Debug.WriteIf(true, "True"); Debug.WriteIf(false, "False"); Debug.WriteLine("Done"); Console.ReadLine(); } static bool IsThursday() { return DateTime.Today.DayOfWeek == DayOfWeek.Thursday; } static bool _flag = true; }
Assert example. Assert sends a strong message to the developer. An assertion interrupts normal operation of the program but does not terminate the application.

Here: We use Assert to catch a condition that should not occur and would be a bug if it did. This is not an exception.

Note: Debug calls are compiled out when in Release mode. Exceptions are always kept in the code.

Exception
C# program that uses Assert method using System; using System.Diagnostics; static class Program { static void Main() { int value = -1; // A. // If value is ever -1, then a dialog will be shown. Debug.Assert(value != -1, "Value must never be -1."); // B. // If you want to only write a line, use WriteLineIf. Debug.WriteLineIf(value == -1, "Value is -1."); } } Output A. The dialog is displayed. B. Message is written to the Output: Value is -1.
Notes, expression arguments. These will be evaluated by the runtime before being converted to a Boolean value (true or false) and then passed as a value to the methods themselves.
A summary. We looked at the Debug.Write methods. Debug.WriteLine is the printf function from C. Permanent error handling with exceptions may be preferable in Release mode compilation.

Note: Thanks to Marco Abusleme for pointing out a small error in the article text.

With TraceListeners, Debug writes to nearly any source. With expression-based methods, it writes only if a condition matches. And with Assert, it makes errors forcefully known.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.