C# - Logical Operators
C# - Logical Operators
Section titled “C# - Logical Operators”What Are Logical Operators in C#?
Section titled “What Are Logical Operators in C#?”Logical operators in C# are used to perform boolean logic on bool operands. They are fundamental for controlling program flow in conditional statements and loops by combining multiple conditions into a single true or false result.
The Core Logical Operators
Section titled “The Core Logical Operators”C# provides three primary logical operators. Assume variable A is true and variable B is false.
| Operator | Symbol | Description | Example |
|---|---|---|---|
| Logical AND | && | Returns true only if both operands are true. | (A && B) is false. |
| Logical OR | || | Returns true if at least one of the operands is true. | (A || B) is true. |
| Logical NOT | ! | Inverts the boolean value of its operand. true becomes false, and false becomes true. | !B is true. |
Key Concept: Short-Circuit Evaluation
Section titled “Key Concept: Short-Circuit Evaluation”Both && (AND) and || (OR) operators perform short-circuiting. This is an important optimization and behavior to understand:
&&(AND): If the first operand isfalse, the second operand is never evaluated because the overall result must befalse.||(OR): If the first operand istrue, the second operand is never evaluated because the overall result must betrue.
Short-Circuiting Example
Section titled “Short-Circuiting Example”public bool IsValid() { Console.WriteLine("IsValid method called."); return true;}
// With &&, IsValid() is NOT called because the first condition is false.bool result1 = (5 < 3) && IsValid();Console.WriteLine($"Result 1: {result1}");
// With ||, IsValid() is NOT called because the first condition is true.bool result2 = (5 > 3) || IsValid();Console.WriteLine($"Result 2: {result2}");
// Output:// Result 1: False// Result 2: TrueNote: C# also has non-short-circuiting bitwise operators & and |, which always evaluate both operands. These are typically used for bit-level manipulation, not for general logical flow control.
Practical Examples of Logical Operators
Section titled “Practical Examples of Logical Operators”Example 1: Login Validation with &&
Section titled “Example 1: Login Validation with &&”We need to verify that both the username and password are correct.
string username = "admin";string password = "pass123";
if (username == "admin" && password == "pass123"){ Console.WriteLine("Login successful.");}else{ Console.WriteLine("Invalid credentials.");}// Output: Login successful.Example 2: Checking Discount Eligibility with ||
Section titled “Example 2: Checking Discount Eligibility with ||”A customer gets a discount if they are a member OR their purchase is over $100.
bool isMember = false;double purchaseAmount = 120.0;
if (isMember || purchaseAmount > 100){ Console.WriteLine("Discount applied.");}else{ Console.WriteLine("No discount available.");}// Output: Discount applied.Example 3: Checking for an Active Session with !
Section titled “Example 3: Checking for an Active Session with !”We want to prompt a user to log in only if they are not already logged in.
bool isLoggedIn = false;
if (!isLoggedIn){ Console.WriteLine("Please log in to continue.");}else{ Console.WriteLine("Welcome back!");}// Output: Please log in to continue.Combining Operators
Section titled “Combining Operators”You can combine multiple operators to create complex rules. Use parentheses () to ensure the correct order of evaluation.
int age = 25;bool hasLicense = true;bool isSober = true;
// You can drive if you are sober AND (you are over 18 AND have a license)if (isSober && (age >= 18 && hasLicense)){ Console.WriteLine("Cleared to drive.");}else{ Console.WriteLine("Not allowed to drive.");}// Output: Cleared to drive.Best Practices for Using Logical Operators
Section titled “Best Practices for Using Logical Operators”- Use Parentheses for Clarity: Always use
()to group conditions, even when operator precedence seems obvious. It makes the code far easier to read, e.g.,if ((user.IsAdmin || user.IsEditor) && !user.IsLockedOut). - Simplify Negations: Instead of
if (isReady == false), use the more concise and readableif (!isReady). - Avoid Redundant Checks: Instead of
if (isValid == true), simply useif (isValid). - Leverage Short-Circuiting: Place the cheaper or more likely-to-fail condition first in an
&&chain. For example, check fornullbefore accessing a member:if (user != null && user.IsAdmin). - Extract to Methods: If a logical condition becomes too complex, extract it into a well-named method or property. Instead of a long
ifstatement, you can haveif (IsEligibleForPromotion(employee)).