Learn/C#/4. Making decisions
Lesson 4 of 15
Sign in

C#, lesson 4

Making decisions

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.

if, else if, else

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.

Comparison and boolean operators

OperatorMeaning

2 exercises to try what you just read.

Exercise 1

Ticket prices

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

==, !=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.

switch expressions and patterns

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.

The conditional operator

For a quick either-or value, use condition ? valueIfTrue : valueIfFalse:

Further reading

  • Selection statements (if, switch)
  • The switch expression
  • Patterns (relational and logical patterns)

A cinema charges by age. Read one whole number, the visitor's age, and print the price:

AgeOutput
below 0Invalid age
0 to 4Price: 0
5 to 17Price: 8
18 to 64Price: 12
65 and abovePrice: 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";
30
Price: 12
2024
2024 is a leap year