×

c# · level 3 · unit 5 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A turns a value into an answer.

The switch statement from Level 2 runs blocks of code. A switch expression is shorter and gives back a value: size switch { "S" => 8.5m, "M" => 10m, _ => 13m }. Each line inside is an : a pattern, an arrow, and the answer it gives.

Arms are tried from top to bottom and the first match wins. The underscore _ is a : a pattern that matches anything, so it goes last as a catch-all. Without one, a value that no arm matches crashes with SwitchExpressionException.

using System;

string[] sizes = { "S", "M", "L", "XL" };
foreach (string size in sizes)
{
    Console.WriteLine($"{size}: {Price(size):0.00}");
}

decimal Price(string size) => size switch
{
    "S" => 8.5m,
    "M" => 10m,
    "L" => 11.75m,
    _ => 13m,
};

The comma after the last arm is allowed, and it keeps adding new arms tidy.