C# Logical Operators
Logical operators are used to combine conditional expressions and return a boolean result (true or false). They are commonly used in decision-making statements like if and while. The most common logical operators in C# are:
Key Logical Operators
&&(Logical AND): Returns true if both conditions are true.||(Logical OR): Returns true if at least one condition is true.!(Logical NOT): Returns true if the condition is false and vice versa.
Example 1: Using Logical AND
// Logical AND Example
int age = 25;
bool hasID = true;
// Condition checks both conditions
if (age >= 18 && hasID) {
Console.WriteLine("You are allowed to enter.");
} else {
Console.WriteLine("Entry denied.");
}
Output:
You are allowed to enter.
Code Explanation: The && operator checks if both conditions are true. Since age is greater than 18 and hasID is true, the output confirms entry.
Example 2: Using Logical OR
// Logical OR Example
bool hasKey = false;
bool knowsPassword = true;
// Only one condition needs to be true
if (hasKey || knowsPassword) {
Console.WriteLine("Access granted.");
} else {
Console.WriteLine("Access denied.");
}
Output:
Access granted.
Code Explanation: The || operator checks if either condition is true. Since knowsPassword is true, access is granted even though hasKey is false.
Example 3: Using Logical NOT
// Logical NOT Example
bool isRaining = false;
// Negate the condition
if (!isRaining) {
Console.WriteLine("It's a sunny day!");
} else {
Console.WriteLine("Bring an umbrella.");
}
Output:
It's a sunny day!
Code Explanation: The ! operator negates the value of isRaining. Since isRaining is false, the logical NOT makes it true, so the program outputs It's a sunny day!.
Key Takeaways
- The
&&operator requires both conditions to be true. - The
||operator requires only one condition to be true. - The
!operator reverses the boolean value of a condition.