c# · level 2 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A checks one value and jumps to its .
A long chain of else if checks the same value again and again. A switch checks it once and jumps to the case label that matches. Each case runs its lines and ends with break, which leaves the switch.
Stack two labels with nothing between them and they share one body, as Medium and Large do here. The label catches every value no case named. A switch works on enums, numbers and text.
C# never lets one case run on into the next. Leave out a break and it refuses with CS0163, or CS8070 on the last label.
using System;
Size size = Size.Large;
switch (size)
{
case Size.Small:
Console.WriteLine("That is 2.50");
break;
case Size.Medium:
case Size.Large:
Console.WriteLine("That is 3.20");
break;
default:
Console.WriteLine("Sorry, we do not make that size");
break;
}
enum Size { Small, Medium, Large, Huge } Ordering a Size.Huge here would land on default.
guess first
The adventurer shouts a command. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
string command = "LOOK";
switch (command.ToLower())
{
case "go":
Console.WriteLine("You walk north.");
break;
case "look":
Console.WriteLine("You see a door.");
break;
default:
Console.WriteLine("Pardon?");
break;
}
your turn
Your turn. Build a game menu.
On line 12, add the label for choice 3. On line 15, add the label that catches every other number. Pick a choice on line 3, then press run.
output
press run to see what happens
fix it
The coin sorter will not start. Fix it!
output
press run to see what happens
- C# says
CS0163on line 9: control cannot fall through from one case label to another. - Every case must end by leaving the switch. Which case on lines 9 and 10 forgets?
- Add
break;on a new line after line 10, then press run.
nailed it
you can jump straight to the answer. :D
- A
switchchecks one value and jumps to its case. - Every case ends with
break. defaultcatches everything the cases missed.
new words in your collection
- switch
- case
- default
This lesson isn’t saved. A free account remembers every lesson you finish.