c# · level 3 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Small letters this time. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Console.WriteLine(Cup("M"));
Console.WriteLine(Cup("m"));
string Cup(string size) => size switch
{
"S" => "small",
"M" => "medium",
"L" => "large",
_ => "unknown size",
};
your turn
Your turn. Price the delivery options.
Fill in a price for each arm, as decimal values like 3.99m. The last gap is the catch-all arm: write the discard, an arrow and a price.
output
press run to see what happens
fix it
The greeter crashes on the third country. Can you fix it?
output
press run to see what happens
- Two lines print, then
SwitchExpressionExceptionstops it. Which country has no arm? - No arm matches
"JP", and there is no catch-all for anything else. - Add the arm
_ => "Hi",as the last line inside the braces, then run.
nailed it
your switches give answers now. :D
- A switch expression turns a value into an answer.
- Arms are tried from top to bottom, and the first match wins.
- End with the discard
_to catch everything else.
new words in your collection
- switch expression
- arm
- discard
This lesson isn’t saved. A free account remembers every lesson you finish.