When debugging a program, you sometimes want to print output to the Output window only if a certain condition is met. For example, if a method returns true, you want to report it. We demonstrate how Debug.WriteLineIf and Debug.WriteIf can be used for this purpose.

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. 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.
This C# example program shows how to use the Debug.WriteLineIf method.
Program that demonstrates WriteLineIf [C#]
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.

Debug-only. The Debug.WriteLineIf and Debug.WriteIf methods are only executed if the program is run in DEBUG mode. This is because they use conditional compilation attributes.
Conditional Method
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.
Visual Studio Tips