Codiqo

Learn C# · lesson 16 of 61 · about 8 minutes

switch and Switch Expressions

Pick the hero's next move: match a value against cases with a switch statement, end every case with break, and turn a value into a result with a switch expression.

What you'll learn

  • Write a switch statement with break
  • Group cases
  • Use a switch expression with _

Many exact matches

After the loot, the player types the hero's next move: rest, run (or flee), or explore. A switch statement compares the value with each case and runs the matching one, and default handles anything else. C#'s switch works with strings as well as numbers and chars.

Every case must end with break. C# never lets one case run on into the next: leave out a break, and the program doesn't compile. Cases with nothing between them can still share code, so case "run": and case "flee": can run the same lines.

The next move

int heroHp = 26;
string next = "rest";
switch (next)
{
    case "rest":
        heroHp += 5;
        Console.WriteLine($"You rest. Hero HP: {heroHp}");
        break;
    case "run":
    case "flee":
        Console.WriteLine("You run back to town.");
        break;
    default:
        Console.WriteLine("You stand still.");
        break;
}

Output

You rest. Hero HP: 31

A switch that gives a value

A switch expression turns a value into a result:

string name = day switch { 1 => "Mon", 2 => "Tue", _ => "?" };

_ matches anything, so it's the catch-all. Arms can also test ranges, like >= 90 => "A", or several values joined with or, and they're checked from the top.

Tip

Read a typed word with (Console.ReadLine() ?? "").ToLower() so capitals match too, and one case per word is enough.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.