Lab: choosing between many options with switch
When a single value selects one of several fixed outcomes, a switch statement says so more plainly than a stack of else if lines.
The task
Store a short code, then display a friendly description for each value the code can hold, with a default for anything unexpected.
C#
string sizeCode = "M";
switch (sizeCode)
{
case "S":
label.Text = "Small";
break;
case "M":
label.Text = "Medium";
break;
default:
label.Text = "Unknown size";
break;
}What to notice
- Each case ends with break, which stops the code falling into the next case.
- The default case catches everything else, which protects you from unexpected input.
- A switch reads like a list of possibilities, which is easier to scan than a condition chain.
Exercise. Add a case for a value that will never occur, then pass that value and watch the default run.
Next, repeat work efficiently with the for loop lab.