C# Booleans
A boolean (bool) is a data type that can hold only one of two values: true or false. Booleans are essential for making decisions in code, such as in if statements and loops.
Many operations, like comparisons (==, >, <) naturally produce boolean results, which can then be stored in a bool variable or used directly in a condition.
bool isTrue = true;Boolean values and comparisons
A bool variable stores true or false. Comparison operators like ==, !=, >, and < evaluate to a boolean result, which is often used directly inside conditions.
Combining booleans
Logical operators && (AND), || (OR), and ! (NOT) let you combine multiple boolean expressions into more complex conditions.
using System;
class Program {
static void Main() {
bool isSunny = true;
Console.WriteLine(isSunny);
Console.WriteLine(10 > 5);
}
}True
TrueisSunny stores a literal bool value, and 10 > 5 evaluates to a bool directly.
using System;
class Program {
static void Main() {
int age = 20;
bool canDrive = age >= 16;
bool hasLicense = true;
Console.WriteLine(canDrive && hasLicense);
}
}True&& combines two boolean expressions, returning true only if both are true.
Key points
- A bool can only be true or false.
- Comparison operators produce boolean results.
- &&, || and ! combine or invert boolean expressions.
- Booleans are essential for conditions in if statements and loops.
