switch statement
A statement that compares one value against a list of cases and runs the matching branch, with a default for everything else.
In more detail
Each case usually ends with break or return; some languages, such as JavaScript, fall through into the next case otherwise, while C# forbids it. To choose a value rather than run steps, a switch expression is often shorter.
Related terms
- switch expression — A switch construct that produces a value, with one arm per case and no fall-through between them.
- pattern matching — Testing a value against a shape, such as a type, a range or the values of its properties, and optionally extracting parts of it in the same step.
- discriminated union — A type made of several object shapes that share one literal field, such as status or type, whose value tells them apart.
- exhaustiveness checking — Having the compiler prove that code handles every possible member of a union, so a newly added member causes a compile error.
- type narrowing — The compiler refining a broad type to a more specific one inside a block, after a check proves which case applies.
Taught in
- The C# Language: Types, Variables, and Flow Control — Modern .NET Core, C# & Enterprise Microservices
- Records, Pattern Matching, and Modern C# — Modern .NET Core, C# & Enterprise Microservices
- never: The Bottom Type And Exhaustive Switch Checking — Production TypeScript
- Discriminated Unions: Tagged Variants And Pattern Matching — Production TypeScript
- Exhaustive Narrowing With never In Production Handlers — Production TypeScript