C# Logical Operators in Conditions
Logical Operators in Conditions
In the Logical Operators chapter, you learned about &&, || and !.
They are most useful inside an if statement. With them, one if can check more than one thing, for example: "Is it warm and sunny?"
&&(AND): both conditions must be true||(OR): at least one condition must be true!(NOT): reverses a condition, so true becomes false, and false becomes true
AND (&&)
Use && when both conditions must be true.
In this example, it is nice weather for a walk only if the temperature is above 20 and it is sunny:
Example
int temperature = 25;
bool isSunny = true;
if (temperature > 20 && isSunny)
{
Console.WriteLine("Nice weather for a walk!");
}
Both conditions are true, so the message is printed. If you change isSunny to false, nothing is printed.
OR (||)
Use || when at least one of the conditions must be true.
In this example, a person gets a cheaper ticket if they are under 12, or if they are 65 or older:
Example
int age = 70;
if (age < 12 || age >= 65)
{
Console.WriteLine("You get a cheaper ticket.");
}
age is 70. The first condition (age < 12) is false, but the second one (age >= 65) is true. One true condition is enough, so the message is printed.
NOT (!)
Use ! to reverse a condition. You can read !isRaining as "is not raining":
Example
bool isRaining = false;
if (!isRaining)
{
Console.WriteLine("You do not need an umbrella.");
}
isRaining is false, so !isRaining is true, and the message is printed.
Replace a Nested If with &&
In the Nested If chapter, you placed an if inside another if. This example prints a message only when both conditions are true:
Example
int age = 20;
bool hasTicket = true;
if (age >= 18)
{
if (hasTicket)
{
Console.WriteLine("Enjoy the movie!");
}
}
When you only need to do something if both conditions are true, one condition with && does the same job:
Example
int age = 20;
bool hasTicket = true;
if (age >= 18 && hasTicket)
{
Console.WriteLine("Enjoy the movie!");
}
Both examples print "Enjoy the movie!". The second one is shorter and easier to read.
Real-Life Example
A common use of && is to check if a number is inside a range.
In this example, a game asks the player to pick a number from 1 to 10. The number must be 1 or more and 10 or less:
Example
int number = 7;
if (number >= 1 && number <= 10)
{
Console.WriteLine("Thank you! You picked " + number + ".");
}
else
{
Console.WriteLine("Please pick a number from 1 to 10.");
}
Try to change number to 15 or 0 in the editor. Then one of the conditions is false, and the else block runs.