2.1.3 Switch Statements

Match One Value to a Named Choice

A Zoo action menu supplies a simple text choice such as "Feed" or "Rest". A switch statement compares one value with several named cases and runs the matching section. It is useful when the alternatives are specific values of the same expression.

Read the Cases
Route a text choice
public string GetActionMessage(string action)
{
    string message;
    switch (action)
    {
        case "Feed":
            message = "Prepare a food portion";
            break;
        case "Rest":
            message = "Allow quiet time";
            break;
        default:
            message = "Choose a supported action";
            break;
    }

    return message;
}

The value of action chooses a section. Each case names a supported value and ends its label with a colon. The default section handles a value that matches neither case. Here every section sets the result before control reaches the return.

The method returns instructions for the selected choice; it does not itself feed an animal. Keeping this example small makes the routing behavior easy to see.

Why break Is Inside Each Section

In this example, break leaves the switch and continues at the statement after it. It does not leave the method: the return message; statement still runs. C# does not allow a nonempty case section simply to flow into the next section as though its case label were absent.

See What Runs After the Choice
Trace Three Inputs
The action value selects Feed, Rest, or default. Each section assigns a message and exits the switch. The method then returns that message.
One selector and a fallback
  • New
  • Changed
  • Removed
Selected sections
Input value Section executed Statement reached after switch
Feed case "Feed" return message
Rest case "Rest" return message
Play default return message
Choose Between switch and if/else if

A switch is clear for a menu code, a boarding group number, or another single value with distinct choices. An if/else if chain is often clearer for ordered ranges or different questions, such as unavailable food followed by insufficient payment.

This page uses ordinary constant cases. You do not need enums, switch expressions, or pattern matching to represent these choices. Those features would add new syntax without helping explain this decision.

Predict a Different Capitalization

Predict the returned message for "Rest", "Play", and "feed". Identify whether each input reaches a named case or default. Then explain where execution goes after the break in the Rest section.

If a new supported choice is added later, it needs a distinct case and a defined result. Existing cases should still produce their original messages, and an unrecognized choice should still have a clear fallback.