Previous Page
Next Page

Declaring bool Variables

In the world of programming (unlike in the real world), everything is black or white, right or wrong, true or false. For example, if you create an integer variable called x, assign the value 99 to x, and then ask, “Does x contain the value 99?”, the answer is definitely true. If you ask, “Is x less than 10?”, the answer is definitely false. These are examples of Boolean expressions. A Boolean expression always evaluates to true or false.

NOTE
The answers to these questions are not definitive for all programming languages. An unassigned variable has an undefined value, and you cannot, for example, say that it is definitely less than 10. Issues such as this one are a common source of errors in C and C++ programs. The Microsoft Visual C# compiler solves this problem by ensuring that you always assign a value to a variable before examining it. If you try to examine the contents of an unassigned variable, your program will not compile.

Microsoft Visual C# provides a data type called bool. A bool variable can hold one of two values: true or false. For example, the following three statements declare a bool variable called areYouReady, assign true to the variable, and then write its value to the console:

bool areYouReady; 
areYouReady = true; 
Console.WriteLine(areYouReady); // writes True

Previous Page
Next Page