Lesson 5: Comparison & Logical Operators in C#
Decision-making is at the heart of every program. Should the user be logged in? Is the order total above a threshold?
Is a form valid? All of these questions are answered using comparison and logical operators
โ they produce bool results that drive your if, while, and for statements.
Comparison Operators
Comparison operators compare two values and always return true or false:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
> | Greater than | 7 > 3 | true |
< | Less than | 2 < 10 | true |
>= | Greater than or equal | 5 >= 5 | true |
<= | Less than or equal | 3 <= 7 | true |
int age = 20;
int minAge = 18;
Console.WriteLine(age == minAge); // False
Console.WriteLine(age != minAge); // True
Console.WriteLine(age >= minAge); // True
Console.WriteLine(age < 100); // True
// Store comparison result in a bool
bool isAdult = age >= minAge; // true
bool isSenior = age >= 65; // false
โ ๏ธ Common Mistake: Don't confuse = (assignment) with == (comparison). Writing if (x = 5) instead of if (x == 5) is a bug โ C# will catch it for value types, but it's easy to get wrong.
Logical Operators
Logical operators combine multiple boolean conditions into one result:
| Operator | Name | Description | Example | Result |
|---|---|---|---|---|
&& | AND | Both must be true | true && false | false |
|| | OR | At least one must be true | true || false | true |
! | NOT | Inverts the value | !true | false |
bool isLoggedIn = true;
bool isAdmin = false;
bool hasLicense = true;
// AND โ both must be true
if (isLoggedIn && isAdmin)
Console.WriteLine("Admin dashboard"); // Not reached
// OR โ at least one must be true
if (isLoggedIn || isAdmin)
Console.WriteLine("Welcome!"); // โ
Printed
// NOT โ inverts the value
if (!isAdmin)
Console.WriteLine("You are not an admin."); // โ
Printed
// Combining operators
if (isLoggedIn && (isAdmin || hasLicense))
Console.WriteLine("Access granted!"); // โ
Printed (logged in AND has license)
Short-Circuit Evaluation
C# uses short-circuit evaluation for && and || โ it stops evaluating
as soon as the result is known. This is both a performance optimization and a safety feature:
string name = null;
// Safe: if name is null, the second condition is never checked
if (name != null && name.Length > 0)
Console.WriteLine("Name is set");
// Without short-circuit, name.Length would throw NullReferenceException
// OR short-circuits differently โ stops when it finds true
bool result = true || SomeExpensiveMethod(); // SomeExpensiveMethod never runs
The Ternary Operator
The ternary operator is a compact way to write simple if/else logic in one line:
// Syntax: condition ? valueIfTrue : valueIfFalse
int age = 20;
string status = age >= 18 ? "Adult" : "Minor";
Console.WriteLine(status); // Adult
int score = 72;
string grade = score >= 90 ? "A"
: score >= 80 ? "B"
: score >= 70 ? "C"
: "F";
Console.WriteLine(grade); // C
Null-Coalescing Operator ??
The ?? operator returns the left side if it's not null, otherwise the right side โ very handy for defaults:
string username = null;
string display = username ?? "Guest";
Console.WriteLine(display); // Guest
string realName = "Alice";
string shown = realName ?? "Anonymous";
Console.WriteLine(shown); // Alice
// Null-coalescing assignment ??= (C# 8+)
username ??= "DefaultUser"; // assigns only if username is null
A Real-World Example: Login Validator
string inputUser = "admin";
string inputPass = "secret123";
int loginAttempts = 2;
bool validUser = inputUser == "admin";
bool validPass = inputPass.Length >= 8;
bool notLocked = loginAttempts < 3;
if (validUser && validPass && notLocked)
{
Console.WriteLine("โ
Login successful!");
}
else if (!notLocked)
{
Console.WriteLine("๐ Account locked. Too many attempts.");
}
else
{
Console.WriteLine("โ Invalid credentials.");
}
// Output: โ
Login successful!
๐ง Final Quiz โ Lesson 5
What does true && false || true evaluate to in C#?
Series Summary โ What You've Learned
Lesson 1: Variables โ declaration, initialization, naming rules, const, var.
Lesson 2: Data Types โ int, double, decimal, bool, char, string, value vs reference.
Lesson 3: Type Conversion โ implicit, explicit casting, Convert, Parse, TryParse.
Lesson 4: Arithmetic & Assignment โ + - * / %, ++/--, +=/-=/*=/, precedence.
Lesson 5: Comparison & Logical โ == != > < >= <=, && || !, ternary, ??.
You've Completed the Series!
You now understand variables, types, and operators in C# โ the foundation of everything you'll build. Ready for the next step?