Skip to main content

How to Switch on Two Values at Once with a Tuple Pattern in C#

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

(isCold, isRaining) switch puts two values into a tuple and matches them as a pair. An arm such as (true, false) => "a warm coat" runs only when the first value is true and the second is false.

Microsoft's patterns reference: You can also match expressions of tuple types against positional patterns. By using this approach, you can match multiple inputs against various patterns. The C# guide on how the values line up: A positional pattern identifies values by their order.

Syntax​

Syntax
(<value1>, <value2>) switch
{
(<pattern1>, <pattern2>) => <result>,
(<pattern1>, _) => <result>,
_ => <otherResult>,
}
PartWhat it is
(<value1>, <value2>)A tuple made from the values to match. It can hold more than two
(<pattern1>, <pattern2>)A tuple pattern: the first pattern checks the first value, the second checks the second, and the arm matches only when both do
_ inside the parenthesesMatches anything in that position
_ => <otherResult>Matches every pair the arms above it don't, when they don't cover them all

The reference on the order of the arms: The switch expression arms are evaluated in text order.

The Example​

A console app called TuplePattern picks what to wear from two answers: is it cold, and is it raining. Two bool values make four combinations, and the switch has one arm for each.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n TuplePattern
cd TuplePattern
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/TuplePattern/TuplePattern.csproj:
Determining projects to restore...
Restored /Users/you/source/TuplePattern/TuplePattern.csproj (in 41 ms).
Restore succeeded.

dotnet new console -n TuplePattern creates a folder named TuplePattern with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or TuplePattern.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the four calls, one per combination:

Program.cs (the calls)
Console.WriteLine($"Cold and raining: {WhatToWear(true, true)}");
Console.WriteLine($"Cold and dry: {WhatToWear(true, false)}");
Console.WriteLine($"Warm and raining: {WhatToWear(false, true)}");
Console.WriteLine($"Warm and dry: {WhatToWear(false, false)}");

Then the method with the switch:

Program.cs (the tuple switch)
static string WhatToWear(bool isCold, bool isRaining)
{
// Both values go into one tuple, and each arm matches the pair.
return (isCold, isRaining) switch
{
(true, true) => "a warm raincoat",
(true, false) => "a warm coat",
(false, true) => "a light raincoat",
(false, false) => "a T-shirt",
};
}
  • (isCold, isRaining) makes a tuple of the two parameters, and switch matches it.
  • (true, false) is a tuple pattern made of two constant patterns. It matches when isCold is true and isRaining is false, in that order.
  • There's no _ arm, because the four arms already cover every pair that two bool values can make.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Cold and raining: a warm raincoat
Cold and dry: a warm coat
Warm and raining: a light raincoat
Warm and dry: a T-shirt

macOS-style terminal window titled Terminal — TuplePattern showing dotnet run printing Cold and raining: a warm raincoat, Cold and dry: a warm coat, Warm and raining: a light raincoat and Warm and dry: a T-shirt

Each call matched exactly one arm. The compiler checked the table too: dotnet build --no-incremental reported 0 Warning(s), so it knows the four arms cover every pair. Leave one out and it warns, as the first mistake below shows.

The Complete File​

macOS-style code window titled Program.cs — TuplePattern showing four Console.WriteLine calls, one for each weather combination, and a WhatToWear method that returns a switch on the tuple of isCold and isRaining with the arms true true, true false, false true and false false

Program.cs
Console.WriteLine($"Cold and raining: {WhatToWear(true, true)}");
Console.WriteLine($"Cold and dry: {WhatToWear(true, false)}");
Console.WriteLine($"Warm and raining: {WhatToWear(false, true)}");
Console.WriteLine($"Warm and dry: {WhatToWear(false, false)}");

static string WhatToWear(bool isCold, bool isRaining)
{
// Both values go into one tuple, and each arm matches the pair.
return (isCold, isRaining) switch
{
(true, true) => "a warm raincoat",
(true, false) => "a warm coat",
(false, true) => "a light raincoat",
(false, false) => "a T-shirt",
};
}

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out a combination, such as (false, false)The build warned warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(false, false)' is not covered. Then WhatToWear(false, false) threw SwitchExpressionException: Non-exhaustive switch expression failed to match its input. with Unmatched value was (False, False).Give every combination an arm, or end with _
Building the tuple in a different order from the patterns, as in (isRaining, isCold) switchNo error, but the wrong arm: cold and dry got a light raincoatKeep the values and the patterns in the same order. The C# guide: A positional pattern identifies values by their order.
A pattern with a different number of positions, as in (true, true, false)error CS8502: Matching the tuple type '(bool isCold, bool isRaining)' requires '2' subpatterns, but '3' subpatterns are present.Write one pattern for each value in the tuple
A broad arm above a narrower one, such as (_, true) above (true, true)error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.Put the narrower arm first

FAQ​

Can one position match anything?​

Yes, with _ in that position. The three arms (_, true) => "a raincoat", (true, false) => "a warm coat" and (false, false) => "a T-shirt" covered all four pairs, and both rainy calls printed a raincoat.

Can a position use other kinds of patterns?​

Yes, any pattern. With an int temperature, (< 10, true) => "a warm raincoat" matched (5, true), and (25, false) went on to _ and got a T-shirt.

Can I write the names in the pattern?​

Yes. The tuple (isCold, isRaining) takes its element names from the two variables, and the arm (isCold: true, isRaining: false) matched cold and dry. The reference: You can use the names of tuple elements and Deconstruct parameters in a positional pattern.

Conclusion​

Put the values in parentheses before switch, and write each arm as a tuple pattern with one pattern per value, in the same order. Cover every combination, or end with _, and put narrower arms above broader ones.

Additional Resources​