Labs ICT
Pro Login

Logical Operators

Logical operators let you combine multiple conditions into one. Instead of checking one thing at a time, you can ask "is this AND that true?" or "is this OR that true?" They're the glue that connects your comparisons into real decision-making logic.

AND (&&)

The && operator returns true only when both conditions are true. If either one is false, the whole thing is false:


int age = 25;
bool hasLicense = true;

if (age >= 18 && hasLicense) {
  Console.WriteLine("You can drive!");
}

// Both conditions must be true:
Console.WriteLine(true && true);    // True
Console.WriteLine(true && false);   // False
Console.WriteLine(false && true);   // False
Console.WriteLine(false && false);  // False
    

OR (||)

The || operator returns true if at least one condition is true. It only returns false when both are false:


bool isWeekend = true;
bool isHoliday = false;

if (isWeekend || isHoliday) {
  Console.WriteLine("No work today!");
}

Console.WriteLine(true || true);    // True
Console.WriteLine(true || false);   // True
Console.WriteLine(false || true);   // True
Console.WriteLine(false || false);  // False
    

NOT (!)

The ! operator flips a boolean value — true becomes false, false becomes true:


bool isRaining = false;

if (!isRaining) {
  Console.WriteLine("Let's go outside!");
}

Console.WriteLine(!true);   // False
Console.WriteLine(!false);  // True
    

Short-Circuit Evaluation

C# is smart about evaluating logical expressions. For &&, if the first condition is false, C# doesn't bother checking the second — the result is already known to be false. For ||, if the first condition is true, the second is skipped.


int x = 5;

// The second condition never runs because the first is false
if (x > 10 && x++ == 6) {
  // Won't enter
}
Console.WriteLine(x);  // Still 5 — x++ never executed

// But with ||, if first is true, second is skipped
if (x < 10 || x++ == 6) {
  // Enters here — first condition was true
}
Console.WriteLine(x);  // Still 5 — second didn't run
    

This is called short-circuit evaluation. It's usually what you want — it makes your code faster and can prevent errors (like checking if something is null before accessing it).

Try it Yourself →