2.1.10 Writing Switch Statements

Overview

In Zoo, a switch can assign a feeding task based on one animalType string. Each case needs an action and a terminating break; in this form. default supplies a value for an unlisted animal so the caller always has a task to display.

string task;
switch (animalType)
{
    case "lion": task = "Prepare meat"; break;
    case "penguin": task = "Prepare fish"; break;
    case "tortoise": task = "Prepare greens"; break;
    default: task = "Check feeding guide"; break;
}
return task;
Write Complete Cases
Write Complete Cases. In Zoo, a switch can assign a feeding task based on one animalType string.
Write Complete Cases
  • New
  • Changed
  • Removed

The switch chooses one branch, then return sends its assigned task to the caller. break; exits the switch; return task; ends the method. Use the exact capitalization of case strings or the input will reach default.

Separate the selection from the final return when learning: assign task in the selected case, exit the switch, then return task once. That makes it easier to inspect task at a breakpoint. If a case is added without assigning task, the shared return may not have a valid value. Use a default case to cover values outside the named cases.

Trace the Outcome

Test each listed animal and one unlisted animal. Confirm task is assigned on every path before the shared return. A switch intended to return a value needs a declared return type and a matching value on every route.