Learn C# · lesson 11 of 61 · about 8 minutes
Logical Operators
Decide whether the hero guards: combine conditions with && (and), || (or) and ! (not).
What you'll learn
- Combine with && and ||
- Flip with !
- Use short-circuiting
Should the hero guard?
The hero only needs to guard when two things are true at once: the player chose defend, and the Slime is still fighting. That's action == "defend" && !slimeDown.
and, or, not
a && b needs both; a || b needs one; !a flips. C# stops early when it knows the answer, so people != 0 && pizza / people >= 2 never divides by zero.
Combining conditions
int age = 15;
bool hasTicket = true;
int people = 0;
Console.WriteLine(age >= 13 && hasTicket);
Console.WriteLine(age < 12 || age > 65);
Console.WriteLine(!hasTicket);
Console.WriteLine(people != 0 && 8 / people >= 2);Output
True
False
False
FalseOne comparison at a time
In maths you might write 0 < hp < 10. C# can't chain comparisons like that: 0 < heroHp is already a bool, and a bool can't be compared with 10. Write both halves and join them: heroHp > 0 && heroHp < 10.
Guarding
string action = "defend";
bool slimeDown = false;
bool guard = action == "defend" && !slimeDown;
Console.WriteLine($"Guarding: {guard}");
Console.WriteLine(action == "Defend");Output
Guarding: True
FalseTip
&& comes before ||, just like × comes before +. When you mix them, add brackets so the order is clear to whoever reads it next.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.