C#
switch statement
multi-variable
programming
software development

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

csharp
1// C# 7 and earlier — single variable only
2string GetDiscount(string memberType)
3{
4    switch (memberType)
5    {
6        case "Gold": return "30% off";
7        case "Silver": return "20% off";
8        case "Bronze": return "10% off";
9        default: return "No discount";
10    }
11}

Switching on a tuple (C# 8+)

Combine the variables into a tuple and match each position:

csharp
1string GetShippingCost(string memberType, string region) => (memberType, region) switch
2{
3    ("Gold", "Domestic")     => "Free",
4    ("Gold", "International") => "$5",
5    ("Silver", "Domestic")    => "$3",
6    ("Silver", "International") => "$10",
7    ("Bronze", _)             => "$15",  // Any region
8    (_, "Domestic")           => "$8",   // Any member type
9    _                         => "$20",  // Default
10};
11
12Console.WriteLine(GetShippingCost("Gold", "International"));  // $5
13Console.WriteLine(GetShippingCost("Bronze", "Domestic"));      // $15

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:

csharp
1string ClassifyTransaction(string type, decimal amount) => (type, amount) switch
2{
3    ("Credit", > 10000)  => "High-value credit",
4    ("Credit", > 1000)   => "Medium credit",
5    ("Credit", _)        => "Small credit",
6    ("Debit", > 5000)    => "Large debit",
7    ("Debit", _)         => "Standard debit",
8    _ => "Unknown transaction"
9};
10
11// With explicit when clause
12string Evaluate(int x, int y) => (x, y) switch
13{
14    (> 0, > 0) => "Both positive",
15    (< 0, < 0) => "Both negative",
16    (0, 0)     => "Origin",
17    var (a, b) when a == -b => "Mirror points",
18    _          => "Mixed"
19};

Matching object properties

Property patterns match against an object's properties:

csharp
1record Order(string Status, decimal Total, string CustomerType);
2
3string GetAction(Order order) => order switch
4{
5    { Status: "Pending", Total: > 1000 }                    => "Requires manager approval",
6    { Status: "Pending", CustomerType: "VIP" }              => "Auto-approve",
7    { Status: "Pending" }                                     => "Standard review",
8    { Status: "Shipped" }                                     => "Track delivery",
9    { Status: "Delivered", Total: > 500 }                    => "Request feedback",
10    _                                                          => "No action"
11};

Nested property patterns

csharp
1record Address(string Country, string State);
2record Customer(string Name, Address Address, bool IsPremium);
3
4decimal GetTaxRate(Customer customer) => customer switch
5{
6    { Address.Country: "US", Address.State: "CA" } => 0.0725m,
7    { Address.Country: "US", Address.State: "TX" } => 0.0625m,
8    { Address.Country: "US" }                       => 0.05m,
9    { Address.Country: "UK" }                       => 0.20m,
10    { IsPremium: true }                              => 0.0m,
11    _                                                 => 0.10m,
12};

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:

csharp
1void ProcessInput(ConsoleKey key, bool shiftPressed)
2{
3    switch (key, shiftPressed)
4    {
5        case (ConsoleKey.Enter, false):
6            Submit();
7            break;
8        case (ConsoleKey.Enter, true):
9            NewLine();
10            break;
11        case (ConsoleKey.Escape, _):
12            Cancel();
13            break;
14        case (ConsoleKey.Tab, false):
15            NextField();
16            break;
17        case (ConsoleKey.Tab, true):
18            PreviousField();
19            break;
20        default:
21            HandleKey(key);
22            break;
23    }
24}

Three or more variables

Tuples can hold any number of elements:

csharp
1string DescribeWeather(string season, int temp, bool raining) => (season, temp, raining) switch
2{
3    ("Summer", > 35, _)        => "Extreme heat warning",
4    ("Summer", > 25, false)    => "Perfect beach day",
5    ("Summer", _, true)        => "Summer rain",
6    ("Winter", < 0, _)         => "Freezing conditions",
7    ("Winter", _, true)        => "Snow likely",
8    ("Spring", > 15, false)    => "Nice spring day",
9    _                           => "Check forecast"
10};

Replacing nested if/else

Before:

csharp
1// Hard to read
2if (role == "Admin" && isActive)
3    return "Full access";
4else if (role == "Admin" && !isActive)
5    return "Suspended admin";
6else if (role == "User" && isActive && isVerified)
7    return "Verified user";
8else if (role == "User" && isActive)
9    return "Unverified user";
10else
11    return "No access";

After:

csharp
1string GetAccess(string role, bool isActive, bool isVerified) =>
2    (role, isActive, isVerified) switch
3    {
4        ("Admin", true, _)     => "Full access",
5        ("Admin", false, _)    => "Suspended admin",
6        ("User", true, true)   => "Verified user",
7        ("User", true, false)  => "Unverified user",
8        _                       => "No access"
9    };

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 throws SwitchExpressionException at runtime.
  • Language version: tuple and property patterns need C# 8.0+, relational patterns (> 0, < 10) need C# 9.0+. Check LangVersion in 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/else reads better. Switch expressions pay off with three or more combined conditions.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data 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.

Practice algorithms