Lesson 12 +10 XP

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
Code

csharp
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)
Code

csharp
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 &amp; and |

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

TL;DR

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