C#, lesson 4
Programs need to react to their input: a game ends when lives reach zero, a shop gives a discount
above some amount. You express that with conditions, expressions that are either true or
false.
C# checks the conditions top to bottom and runs only the first block whose condition is
true. The else block runs when nothing above matched. A condition must be a bool; C# will
not quietly treat 0 or an empty string as false.
| Operator | Meaning |
|---|
2 exercises to try what you just read.
==, != | equal, not equal |
<, <= | less than (or equal) |
>, >= | greater than (or equal) |
&& | and: both sides true |
|| | or: at least one side true |
! | not: flips true and false |
For strings, == compares the text, so answer == "yes" does what you expect. To ignore case,
use string.Equals(answer, "YES", StringComparison.OrdinalIgnoreCase).
&& and || short-circuit: if the left side already decides the result, the right side is
skipped. That makes guards like name != null && name.Length > 3 safe.
When one value decides between several results, a switch expression is shorter and clearer
than an if chain. Each arm has a pattern, =>, and a result. The arms are tried in order,
and _ (the discard) matches anything left:
Patterns can also compare with relational operators, which makes range checks very readable:
The compiler warns you if some values are not covered, and the program throws an exception at
run time if no arm matches, so finish with a _ arm unless you have covered every case.
For a quick either-or value, use condition ? valueIfTrue : valueIfFalse:
A cinema charges by age. Read one whole number, the visitor's age, and print the price:
| Age | Output |
|---|---|
| below 0 | Invalid age |
| 0 to 4 | Price: 0 |
| 5 to 17 | Price: 8 |
| 18 to 64 | Price: 12 |
| 65 and above | Price: 7 |
A switch expression with relational patterns fits this nicely, but an if chain works too.
Sample input:
Sample output:
A year is a leap year if it is divisible by 4, except years divisible by 100, which are not
leap years unless they are also divisible by 400. Read a year and print either
<year> is a leap year or <year> is not a leap year.
Write the rule as one bool expression using %, && and ||.
Sample input:
Sample output:
int score = 72;
if (score >= 90)
{
Console.WriteLine("Gold");
}
else if (score >= 70)
{
Console.WriteLine("Silver");
}
else
{
Console.WriteLine("Keep practising");
}bool weekend = day == "Sat" || day == "Sun";
if (age >= 13 && age <= 19)
{
Console.WriteLine("Teenager");
}string sound = animal switch
{
"cat" => "Meow",
"dog" => "Woof",
"cow" or "ox" => "Moo",
_ => "..."
};string size = shoeSize switch
{
< 36 => "Small",
>= 36 and <= 42 => "Medium",
_ => "Large"
};string label = count == 1 ? "item" : "items";30Price: 1220242024 is a leap year