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); // False

Boolean 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); // False

Comparison operators

OperatorMeaningExample (x = 5)
==Equal tox == 5 is True
!=Not equal tox != 3 is True
>Greater thanx > 8 is False
<Less thanx < 8 is True
>=Greater than or equal tox >= 5 is True

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.
Note: Do not confuse the assignment operator = with the comparison operator ==. Writing if (x = 5) is an error in C#, because = assigns a value while == checks for equality.

Exercise: C# Booleans

Can you write if (1) in C# to check a condition, the way you might in C?