Lesson 12 +10 XP

Comparison & Logical Operators

Comparison & Logical Operators

Comparison operators compare values and return true or false. Logical operators combine bool results.

Comparison operators

OperatorNameExample
==equal tox == y
!=not equalx != y
>greater thanx > y
<less thanx < y
>=greater than or equalx >= y
<=less than or equalx <= y
int x = 5;
int y = 3;
Console.WriteLine(x > y);   // True
Console.WriteLine(x == y);  // False

Logical operators

OperatorNameExample
&&logical andx < 5 && x < 10
``logical or`x < 5x < 4`
!logical not!(x < 5)
int x = 5;
Console.WriteLine(x > 3 && x < 10);  // True  (both must be true)
Console.WriteLine(x > 3 || x < 4);   // True  (at least one true)
Console.WriteLine(!(x > 3));         // False (negates the result)

Note on single & and |

& and | also exist but always evaluate both sides. The doubled forms && and || short-circuit: they skip evaluating the right side if the answer is already known.

TL;DR

  • Comparison operators return true/false.
  • && needs both sides true; || needs at least one.
  • ! flips a boolean.
  • && and || short-circuit; & and | do not.