Skip to content

C# - Logical Operators

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.

C# provides three primary logical operators. Assume variable A is true and variable B is false.

OperatorSymbolDescriptionExample
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.

Both && (AND) and || (OR) operators perform short-circuiting. This is an important optimization and behavior to understand:

  • && (AND): If the first operand is false, the second operand is never evaluated because the overall result must be false.
  • || (OR): If the first operand is true, the second operand is never evaluated because the overall result must be true.
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: True

Note: 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.

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.

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 readable if (!isReady).
  • Avoid Redundant Checks: Instead of if (isValid == true), simply use if (isValid).
  • Leverage Short-Circuiting: Place the cheaper or more likely-to-fail condition first in an && chain. For example, check for null before 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 if statement, you can have if (IsEligibleForPromotion(employee)).