BeginnerLesson 4 of 205 min read

Decisions and Loops: if, switch Expressions and Pattern Matching

Learn if statements, switch expressions with patterns, for, while, foreach loops, break and continue, applied to a café price list with every total verified by a second calculation.

In this lesson you will

  • Make decisions with if and switch
  • Use pattern matching
  • Repeat work with loops
  • Verify a loop independently

About 28 minutes

Happy hour prices

Omar charges less for coffee between 14:00 and 16:00 and has a loyalty discount for regulars. The program must decide, for each order, which price applies, and then go through all the orders. Decisions use if and switch, and repetition uses for, while and foreach.

An if statement runs a block when its condition is true. A switch expression returns a value and is the modern way to choose between several cases: it uses arrows, has no fall-through, and the compiler warns when the cases do not cover every possibility. Patterns make switch much more powerful: you can match on ranges with relational patterns such as >= 14 and < 16, on types, and on combinations with and, or and not. A for loop has a start, a condition and a step, while checks its condition first, foreach visits every item of a collection, and break and continue leave a loop or skip to the next round.

Construct Use it when
if / else One or two conditions
switch expression Choosing by value, range or type
for You know the number of rounds
while You repeat until something changes
foreach You visit every item of a collection
static int Price(string drink, int hour) => (drink, hour) switch
{
    ("coffee", >= 14 and < 16) => 250,
    ("coffee", _) => 320,
    ("tea", _) => 210,
    ("cake", < 12) => 280,
    ("cake", _) => 350,
    _ => throw new ArgumentException($"unknown drink {drink}")
};
string[] drinks = { "coffee", "tea", "cake" };
int[] hours = { 9, 14, 15, 16, 20 };
int total = 0;
foreach (var h in hours)
{
    foreach (var d in drinks)
    {
        int p = Price(d, h);
        total += p;
    }
    Console.WriteLine($"hour {h}: coffee {Price("coffee", h)}, tea {Price("tea", h)}, cake {Price("cake", h)}");
}
Console.WriteLine($"sum of all combinations: {total}");
int n = 0, steps = 0;
while (n < 100) { n += 7; steps++; }
Console.WriteLine($"while: reached {n} after {steps} steps");
int evens = 0;
for (int i = 1; i <= 20; i++)
{
    if (i % 2 == 1) continue;
    if (i > 14) break;
    evens += i;
}
Console.WriteLine($"sum of even numbers up to 14: {evens}");
object[] things = { 42, "tea", 3.5, null };
foreach (var t in things)
{
    string kind = t switch { int i when i > 40 => "big int", int => "int", string s => $"string of {s.Length}", null => "nothing", _ => "other" };
    Console.WriteLine($"{t ?? "null"} is {kind}");
}
Program.cs(34,37): warning CS8625: Cannot convert null literal to non-nullable reference type. [app.csproj]
hour 9: coffee 320, tea 210, cake 280
hour 14: coffee 250, tea 210, cake 350
hour 15: coffee 250, tea 210, cake 350
hour 16: coffee 320, tea 210, cake 350
hour 20: coffee 320, tea 210, cake 350
sum of all combinations: 4190
while: reached 105 after 15 steps
sum of even numbers up to 14: 56
42 is big int
tea is string of 3
3.5 is other
null is nothing

The switch expression chose the price from the pair of drink and hour: coffee costs 250 at 14:00 and 15:00 because the hour pattern >= 14 and < 16 matches, and 320 at other hours, tea always costs 210, and cake is cheaper before noon. The program added up every combination of five hours and three drinks, 4190 cents in total. A drink that is not on the list throws an ArgumentException, so a mistake in the menu cannot silently give a price of zero. The while loop added 7 until it passed 100 and stopped at 105 after 15 steps, and the last loop used continue to skip odd numbers and break to stop after 14, adding 2 + 4 + … + 14 = 56.

The last loop shows type patterns. The switch looked at what each object really was: the int 42 matched “big int” because of the guard when i > 40, the string was reported with its length, the double fell to the default case, and null had its own pattern. Pattern matching replaces long chains of if and casts with one readable expression. The first line of the output is a compiler warning, CS8625, because null was placed in an array of non-nullable objects with nullable checking switched on. It is a warning and not an error, and lesson 17 explains nullable reference types.

Check by hand: coffee at the five hours costs 320 + 250 + 250 + 320 + 320 = 1,460. Tea is 5 x 210 = 1,050. Cake is 280 at hour 9 and 350 at the other four hours, 280 + 1,400 = 1,680. The three add up to 1,460 + 1,050 + 1,680 = 4190, the total the program printed, and an independent Python calculation of the same table gave 4190.

Reading a loop on paper

When a loop confuses you, write its variables in a small table, one row per round. For the while loop above, n goes 7, 14, 21 and so on while steps goes 1, 2, 3, and the loop ends in the round where n reaches 105 and the condition n < 100 becomes false. Doing this by hand for two or three rounds is the quickest way to spot an off-by-one mistake, and it is how you check that the boundary conditions of a loop do what you intended before you run it.

Cover every case

A switch expression that misses a case throws at run time when no arm matches. Add a default arm that throws a clear error, as the program does.

Use patterns instead of casts

x is int i, switch arms with types and guards with when read better than manual casts and chains of else if.

About this course

Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8. Relational and logical patterns need C# 9 or later.

Practice

Add a loyalty discount of 10 percent for orders of three or more items, and a surcharge for takeaway orders. Test the boundaries at 13:59, 14:00, 15:59 and 16:00, and recompute one price by hand.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does a switch expression return?

  1. A value
  2. Nothing
  3. Always text
  4. A class

It can be assigned to a variable.

What does the pattern >= 14 and < 16 match?

  1. Hours 14 to 16 inclusive
  2. Only 16
  3. All hours
  4. Hours 14 and 15

The upper bound is exclusive.

What does continue do?

  1. Leaves the loop
  2. Stops the program
  3. Repeats the round
  4. Skips to the next round

break leaves the loop.

What is foreach for?

  1. Creating arrays
  2. Sorting
  3. Visiting every item of a collection
  4. Reading files only

No index needed.

Why add a default arm that throws?

  1. Because switch is slow
  2. To save memory
  3. So unknown input is not silently priced
  4. It is required

Fail loudly.

Summary

  • if and switch expressions make decisions; patterns match values, ranges and types.
  • for, while and foreach repeat work.
  • break leaves and continue skips.
  • Verify loop results with a second calculation.

Next lesson

Lesson 5 covers methods: parameters, optional and named arguments, ref and out.

Questions

When should I use if instead of switch?

For one or two simple conditions. Use a switch when you compare one value against several cases or patterns.

What is a guard?

A when condition added to a pattern, as in int i when i > 40.

Can loops be nested?

Yes. The example uses a foreach inside a foreach.

Progress is saved in this browser.