<aside> Comparison operators and logical operations are essential for creating conditional logic in C# programs. They form the foundation of decision-making in your code.

</aside>

⚖️ Comparison Operators

Comparison operators evaluate relationships between values and return boolean (true/false) results.

Operator Name Example Result
< Less than 5 < 10 true
<= Less than or equal to 5 <= 5 true
> Greater than 10 > 5 true
>= Greater than or equal to 10 >= 11 false
== Equal to 5 == 5 true
!= Not equal to 5 != 10 true

🔗 Logical Operators

Operator Name Description
&& AND Both conditions must be true
! NOT Inverts the boolean value

📝 Example Usage

// Basic comparison
int age = 25;
bool isAdult = age >= 18;  // true

// Combining conditions with AND
bool hasLicense = true;
bool canDrive = isAdult && hasLicense;  // true

// Using OR operator
bool isHoliday = false;
bool isWeekend = true;
bool canRest = isHoliday || isWeekend;  // true

// Using NOT operator
bool isWorking = !isHoliday;  // true

🎯 Common Use Cases

// Age verification
if (age >= 18 && hasLicense)
{
    Console.WriteLine("Can drive");
}

// Temperature check
int temperature = 25;
if (temperature < 0 || temperature > 30)
{
    Console.WriteLine("Extreme temperature!");
}

// Password validation
string password = "secret123";
bool isValid = password.Length >= 8 && password.Contains("123");

<aside> 💡 Best Practices: • Use parentheses to make complex conditions more readable • Combine operators carefully to avoid logical errors • Consider the order of evaluation in complex conditions • Use meaningful variable names for boolean values

</aside>

<aside> ⚠️ Common Pitfalls: • Confusing == (comparison) with = (assignment) • Not considering all possible conditions • Over-complicating logical expressions • Forgetting that && evaluates before ||

</aside>

🔄 Short-Circuit Evaluation

C# uses short-circuit evaluation for logical operators:

// Example of short-circuit evaluation
bool IsValid(string text)
{
    // If text is null, Length isn't checked (prevents NullReferenceException)
    return text != null && text.Length > 0;
}