C# switch on multiple variables with tuple patterns
Codemia Knowledge Hub ·
To switch on several variables in C#, wrap them in a tuple and match tuple patterns: (x, y) switch { (1, 2) => ..., _ => ... }. Tuple patterns and property patterns arrived in C# 8.0; before that, switch matched a single value. This replaces nested if/else chains with one readable pattern match.
The single-variable switch
Switching on a tuple (C# 8+)
Combine the variables into a tuple and match each position:
The _ discard matches any value. Patterns are checked top to bottom and the first match wins.
Relational patterns and when guards
Use relational patterns such as > 10000 inside the tuple, or add a when clause for conditions that relate the values to each other:
Matching object properties
Property patterns match against an object's properties:
Nested property patterns
The dotted form { Address.Country: "US" } is an extended property pattern, which requires C# 10. In C# 8 and 9, write it as { Address: { Country: "US" } }.
Tuple patterns in a switch statement
The statement form uses case labels with tuple patterns:
Three or more variables
Tuples can hold any number of elements:
Replacing nested if/else
Before:
After:
Mistakes to avoid
- Unreachable patterns: a broad pattern above a specific one makes the specific one unreachable. The compiler warns about this, so put specific patterns first.
- Non-exhaustive switch expressions: every possible input must be handled. Leaving out
_when not all cases are covered produces a compiler warning, and an unmatched input throwsSwitchExpressionExceptionat runtime. - Language version: tuple and property patterns need C# 8.0+, relational patterns (
> 0,< 10) need C# 9.0+. CheckLangVersionin your.csproj. - Values that change: the result is based on the values at the time of the switch, not when the result is used. Copy them into local variables first if mutability is a concern.
- Overuse: for a simple two-way condition,
if/elsereads better. Switch expressions pay off with three or more combined conditions.
Related reading
- Multiline editing in Visual Studio Code
- Multiline string literal in C#
- Multiple actions were found that match the request in Web Api
- Multiple awaits vs Task.WaitAll - equivalent?
- Multiple DbContext in .NET Aspire
- Multiple file-extensions searchPattern for System.IO.Directory.GetFiles
- MultipleActiveResultSetsTrue or multiple connections?
- Multiply TimeSpan in .NET

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.