C# Booleans
Very often in programming you need a value that can only be true or false. For this, C# provides the bool type, the foundation of every decision your program makes.
Boolean Values
A Boolean variable is declared with the bool keyword and can hold only one of two values: true or false. These are keywords in C#, written in lowercase and without quotes, since they are not text.
Declaring booleans
bool isOnline = true;
bool isFinished = false;
Console.WriteLine(isOnline); // True
Console.WriteLine(isFinished); // FalseBoolean Expressions
More often, a Boolean value is the result of a comparison rather than something you type directly. When you compare two values, C# evaluates the expression and returns true or false. The comparison operators include == (equal to), != (not equal to), > (greater than), and < (less than).
Comparing values
int score = 75;
int passMark = 50;
Console.WriteLine(score > passMark); // True
Console.WriteLine(score == passMark); // FalseComparison operators
Booleans Drive Decisions
The real power of Booleans appears when you use them with conditional statements such as if. The program checks whether the Boolean expression is true and runs the matching block of code, which is how software chooses what to do.
Using a boolean in an if
int age = 20;
bool isAdult = age >= 18;
if (isAdult)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a minor.");
}- A bool holds only true or false.
- Comparison operators like == and > produce Boolean results.
- Booleans are the condition that if statements and loops rely on.
Exercise: C# Booleans
Can you write if (1) in C# to check a condition, the way you might in C?