C# ยท Chapter 15 of 46

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.

Syntax
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.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    bool isSunny = true;
    Console.WriteLine(isSunny);
    Console.WriteLine(10 > 5);
  }
}
Output
True
True

isSunny stores a literal bool value, and 10 > 5 evaluates to a bool directly.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    int age = 20;
    bool canDrive = age >= 16;
    bool hasLicense = true;
    Console.WriteLine(canDrive && hasLicense);
  }
}
Output
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.
๐Ÿ’ก Note: Unlike some languages, C# does not treat 0 or empty strings as false โ€” only the literal `false` value counts.

๐Ÿ“ Quick Quiz

1. What are the only two values a bool can hold?

2. What does 10 > 5 evaluate to?

3. Which operator means logical NOT?