Since C# 9.0, the language has supported Pattern Matching, overview of the pattern syntax can be found here.
Using this as a reference, it's easy to implement very similar functionality for each of the above cases in C#:
foreach (int n in Enumerable.Range(0, 101)) {
Console.WriteLine((n % 5, n % 2, n % 7) switch {
(0, var y, var z) => $"First is `0`, `y` is {y}, and `z` is {z}",
(1, _, _) => "First is `1` and the rest doesn't matter",
(_, _, 2) => "last is `2` and the rest doesn't matter",
(3, _, 4) => "First is `3`, last is `4`, and the rest doesn't matter",
_ => "It doesn't matter what they are",
});
}
Couple things of particular note here:
- We must consume the result of the
switch
expression.
For instance, this causes an error:
foreach (int n in Enumerable.Range(0, 101)) {
// causes:
// error CS0201: Only assignment, call, increment,
// decrement, await, and new object expressions
// can be used as a statement
(n % 5, n % 2, n % 7) switch {
(0, var y, var z) => Console.WriteLine($"First is `0`, `y` is {y}, and `z` is {z}"),
(1, _, _) => Console.WriteLine("First is `1` and the rest doesn't matter"),
(_, _, 2) => Console.WriteLine("last is `2` and the rest doesn't matter"),
(3, _, 4) => Console.WriteLine("First is `3`, last is `4`, and the rest doesn't matter"),
_ => Console.WriteLine("It doesn't matter what they are"),
};
}
- If we want to use
..
to throw away 0 or more positional items, we'll need C# 11.0 or greater, and we'd need to instantiate it as a List
or array
instead, and switch to using square brackets []
rather than parentheses ()
, like so:
foreach (int n in Enumerable.Range(0, 101)) {
// this can also be any of:
// `new int[] { n % 5, n % 2, n % 7 }`,
// `new[] { n % 5, n % 2, n % 7 }`,
// `{ n % 5, n % 2, n % 7 }`
Console.WriteLine(new List<int> { n % 5, n % 2, n % 7 } switch {
[0, var y, var z] => $"First is `0`, `y` is {y}, and `z` is {z}",
[1, ..] => "First is `1` and the rest doesn't matter",
[.., 2] => "last is `2` and the rest doesn't matter",
[3, .., 4] => "First is `3`, last is `4`, and the rest doesn't matter",
_ => "It doesn't matter what they are",
});
}