TheDeveloperBlog.com


C# Debug.WriteLineIf, WriteIf

Debug.WriteLineIf prints output only if a condition is met. As an example, if a method returns true, we want to report it. We demonstrate how Debug.WriteLineIf and Debug.WriteIf can be used for this purpose.


Example. The Debug.WriteLineIf and Debug.WriteIf methods have a first argument of bool type. This can be any expression that evaluates to true or false, including a method call, property access, or field load.

Bool

This example prints Thursday if the IsThursday method evaluates to true. It also uses a bool field and an expression that is evaluated at runtime. Finally, the constants true or false can also be used.

True, False
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;
}

WriteLineIf versus WriteIf. The WriteLineIf and WriteIf methods are identical except that WriteLineIf appends a newline sequence to the output after it writes the data. If the condition is false, no action is taken.

WriteLineIf versus Assert. The WriteLineIf method is different from Assert because it yields a less intrusive error message. It only prints something to the output window instead of causing a dialog box to appear.

Assert Method

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

Conditional Method

Summary. We looked at the Debug.WriteLineIf and Debug.WriteIf methods found in the System.Diagnostics namespace. These methods receive a bool argument, which can be any expression that evaluates to true or false, including a bool variable.