← C# from Scratch
Lesson 15 of 39 · 10 XP
switch
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
switch picks a branch by value. In C# it works with strings too:
switch (cmd)
{
case "w": y++; break;
case "s": y--; break;
case "q":
case "exit": // two values — one branch
running = false;
break;
default:
Console.WriteLine("?");
break;
}
Unlike C, you can't "fall through" from a non-empty case into the next one — the compiler requires break
(or return). This protects you from a common mistake.
The modern form is a switch expression, which produces a value directly:
string day = n switch
{
1 => "Monday",
6 or 7 => "Weekend",
_ => "Weekday", // _ means "everything else"
};
Task. Read the number of a day of the week (1–7). Print its name in English (Monday … Sunday),
and Unknown for any other number.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.