Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

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.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.