Advertisement
Beginner C# Lesson 5 of 5 ยท Final

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.

Advertisement

Comparison Operators

Comparison operators compare two values and always return true or false:

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
>Greater than7 > 3true
<Less than2 < 10true
>=Greater than or equal5 >= 5true
<=Less than or equal3 <= 7true
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:

OperatorNameDescriptionExampleResult
&&ANDBoth must be truetrue && falsefalse
||ORAt least one must be truetrue || falsetrue
!NOTInverts the value!truefalse
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
Advertisement

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, ??.

๐ŸŽ–๏ธ Series Complete

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?

Browse Next Topics โ†’ Review from Lesson 1