Loading...

C# Boolean Operations

Learn how boolean operations work in C#, including the bool type, comparisons, and logical operators like &&, ||, and ! with examples.

In C#, the bool data type can only take two values: true or false. It is directly used in control flow structures such as if, while, and for. Additionally, logical operators (&&, ||, !) can be used to create more complex conditions.


Simple Bool Usage


bool valid = true;

if (valid)
{
    Console.WriteLine("Condition is true, continuing process.");
}
Avoid comparisons like if (valid == true). A boolean variable can be used directly: if (valid).

Comparison Result as Bool

Comparison operators (>, <, ==, !=, etc.) always return a bool result.


int number = 20;
bool positive = number > 0;

Console.WriteLine(positive); // true

Logical Operators


bool a = true;
bool b = false;

Console.WriteLine(a && b); // false (and)
Console.WriteLine(a || b); // true  (or)
Console.WriteLine(!a);     // false (not)

Direct Use in Conditions

Bool variables can be used directly as conditions in structures like if and while.


bool proceed = true;
int counter = 0;

while (proceed)
{
    Console.WriteLine("Counter: " + counter);
    counter++;

    if (counter == 3)
        proceed = false;
}

User Input with Bool

User input values can be converted into logical expressions.


Console.Write("Do you want to continue? (Y/N): ");
string answer = Console.ReadLine().Trim().ToUpper();

bool proceed = (answer == "Y");

if (proceed)
    Console.WriteLine("Program continues...");
else
    Console.WriteLine("Program terminated.");

TL;DR

  • bool can only take true or false.
  • Comparison operators always return a bool.
  • &&, ||, ! are used for logical operations.
  • Bools can be used directly in conditions.
  • User inputs can be converted into logical expressions.