Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Debug.WriteLineIf, WriteIf

This C# example program uses the Debug.WriteLineIf method from System.Diagnostics.

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.



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");


    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.

Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf