C# Logical Operators in if Statements

Logical operators in C# are used to combine multiple conditions within an if statement. The primary logical operators are && (AND), || (OR), and ! (NOT). Using logical operators can reduce the need for nested if statements and improve code readability.

Key Topics

1. Logical AND Operator (&&)

The && operator returns true only if both operands are true.

Example: Checking Multiple Conditions

int age = 25;
bool hasTicket = true;
if (age >= 18 && hasTicket)
{
    Console.WriteLine("Access granted.");
}
else
{
    Console.WriteLine("Access denied.");
}

Output:

Access granted.

2. Logical OR Operator (||)

The || operator returns true if at least one of the operands is true.

Example: Allowing Multiple Options

string day = "Saturday";
if (day == "Saturday" || day == "Sunday")
{
    Console.WriteLine("It's the weekend!");
}
else
{
    Console.WriteLine("It's a weekday.");
}

Output:

It's the weekend!

3. Logical NOT Operator (!)

The ! operator inverts the truth value of a boolean expression.

Example: Inverting a Condition

bool isRaining = false;
if (!isRaining)
{
    Console.WriteLine("You don't need an umbrella.");
}

Output:

You don't need an umbrella.

4. Combining Multiple Conditions

You can combine multiple logical operators to create complex conditions.

Example: Complex Condition

int temperature = 20;
bool isSunny = true;
if ((temperature >= 15 && isSunny) || temperature >= 25)
{
    Console.WriteLine("It's a good day for a walk.");
}

Output:

It's a good day for a walk.

5. Short-Circuit Evaluation

C# uses short-circuit evaluation with logical operators. For &&, if the first condition is false, the second condition is not evaluated. For ||, if the first condition is true, the second condition is not evaluated.

Example: Avoiding Null Reference Exception

string text = null;
if (text != null && text.Length > 0)
{
    Console.WriteLine("Text is not empty.");
}

Explanation: Since text != null is false, text.Length > 0 is not evaluated, preventing a NullReferenceException.

6. Best Practices for Using Logical Operators

  • Use parentheses to make complex conditions clear.
  • Be aware of short-circuit evaluation to prevent runtime errors.
  • Simplify conditions where possible to improve readability.
  • Avoid overly complex conditions that may confuse readers.

Key Takeaways

  • Logical operators combine multiple conditions in an if statement.
  • && requires both conditions to be true; || requires at least one.
  • ! negates a boolean expression.
  • Short-circuit evaluation can optimize performance and prevent errors.
  • Proper use of logical operators can reduce code complexity and improve readability.