Logical Operators
Logical operators allow you to combine multiple conditions. They're essential for making complex decisions in your programs.
The Three Logical Operators
| Operator | Name | Description |
|---|---|---|
&& | AND | True if BOTH conditions are true |
| ` | ` | |
! | NOT | Reverses the boolean value |
AND Operator (&&)
Returns true only when both conditions are true:
csharp1bool a = true;2bool b = true;3bool c = false;45Console.WriteLine(a && b); // true (both true)6Console.WriteLine(a && c); // false (one is false)7Console.WriteLine(c && c); // false (both false)
Truth Table for AND
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
Practical AND Examples
csharp1int age = 25;2bool hasLicense = true;34// Must be 18+ AND have a license to drive5bool canDrive = age >= 18 && hasLicense;6Console.WriteLine($"Can drive: {canDrive}"); // true78// Check if value is in range9int score = 85;10bool isValidScore = score >= 0 && score <= 100;11Console.WriteLine($"Valid score: {isValidScore}"); // true
OR Operator (||)
Returns true when at least one condition is true:
csharp1bool a = true;2bool b = false;34Console.WriteLine(a || b); // true (at least one is true)5Console.WriteLine(b || b); // false (both are false)
Truth Table for OR
| A | B | A || B |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
Practical OR Examples
csharp1string day = "Saturday";23// Weekend is Saturday OR Sunday4bool isWeekend = day == "Saturday" || day == "Sunday";5Console.WriteLine($"Weekend: {isWeekend}"); // true67// Discount for seniors OR students8int age = 70;9bool isStudent = false;1011bool getsDiscount = age >= 65 || isStudent;12Console.WriteLine($"Gets discount: {getsDiscount}"); // true
NOT Operator (!)
Reverses a boolean value:
csharp1bool isActive = true;23Console.WriteLine(!isActive); // false4Console.WriteLine(!false); // true
Practical NOT Examples
csharp1bool isLoggedIn = false;23// Check if NOT logged in4if (!isLoggedIn)5{6 Console.WriteLine("Please log in");7}89// Check if string is NOT empty10string name = "Alice";11bool hasName = !string.IsNullOrEmpty(name);12Console.WriteLine($"Has name: {hasName}"); // true
Combining Operators
You can combine multiple logical operators:
csharp1int age = 25;2bool hasID = true;3bool isVIP = false;45// Complex condition6bool canEnter = (age >= 21 && hasID) || isVIP;7Console.WriteLine($"Can enter: {canEnter}"); // true89// Another example10int score = 75;11int attempts = 2;1213bool passed = score >= 70 && attempts <= 3;14Console.WriteLine($"Passed: {passed}"); // true
Operator Precedence
Logical operators have precedence (evaluated in this order):
!(NOT) - highest&&(AND)||(OR) - lowest
csharp1bool a = true;2bool b = false;3bool c = true;45// Without parentheses6bool result1 = a || b && c; // true (AND evaluated first)7// Equivalent to: a || (b && c) = true || false = true89// With parentheses to change order10bool result2 = (a || b) && c; // true11// (true || false) && true = true && true = true
Use parentheses to make your intentions clear:
csharp1// Unclear2bool unclear = a || b && c || !d;34// Clear5bool clear = a || (b && c) || (!d);
Short-Circuit Evaluation
C# uses short-circuit evaluation for && and ||:
csharp1// AND: if first is false, second is not evaluated2bool result = false && SomeFunction(); // SomeFunction() never runs34// OR: if first is true, second is not evaluated5bool result = true || SomeFunction(); // SomeFunction() never runs
Why It Matters
csharp1string name = null;23// Safe: if name is null, Length is never accessed4bool isValid = name != null && name.Length > 0;56// Unsafe: would throw NullReferenceException7// bool isValid = name.Length > 0 && name != null;
Short-circuit evaluation allows safe null checks:
csharp1// Check for null first, then access properties2if (user != null && user.IsActive)3{4 Console.WriteLine("User is active");5}
Practical Examples
csharp1// Login validation2string username = "admin";3string password = "secret123";45bool validUsername = username.Length >= 3;6bool validPassword = password.Length >= 8;7bool canLogin = validUsername && validPassword;89Console.WriteLine($"Can login: {canLogin}"); // true1011// Shipping eligibility12decimal orderTotal = 75.00m;13bool isPremiumMember = false;14string country = "USA";1516bool freeShipping = (orderTotal >= 50 && country == "USA") || isPremiumMember;17Console.WriteLine($"Free shipping: {freeShipping}"); // true1819// Grade calculation20int examScore = 85;21int homeworkScore = 90;22bool attendedClass = true;2324bool passedCourse = attendedClass && (examScore >= 60 || homeworkScore >= 80);25Console.WriteLine($"Passed: {passedCourse}"); // true
Summary
In this lesson, you learned:
&&(AND): true when both conditions are true||(OR): true when at least one condition is true!(NOT): reverses the boolean value- Operator precedence:
!>&&>|| - Short-circuit evaluation skips unnecessary checks
- Use parentheses to clarify complex conditions
Next, we'll learn how to read user input for interactive programs.