Modern C# · Lesson 4

Switch expressions

Return one value from an exhaustive set of cases.

How it works

A switch expression turns a decision into a value that can be assigned or returned directly. Each arm consists of a pattern, an arrow, and a result. The relational patterns here classify a score, with negative values rejected before the ordinary ranges. The final discard arm makes the expression total for every integer. It also documents what happens above the earlier thresholds.

Boundary values deserve special attention: sixty belongs to pass because the earlier arm only accepts values less than sixty. A switch expression is most helpful when each branch produces a short result and none hides unrelated side effects.

Test minus one, zero, fifty-nine, sixty, one hundred, and one hundred one. Write the expected label beside each input before changing the program.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var score = 60;
var result = score switch
{
    < 0 => "invalid",
    < 60 => "retry",
    <= 100 => "pass",
    _ => "invalid"
};
Console.WriteLine(result);

Expected output

pass
Try this
Read each range together with the ranges that came before it.