tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Pure magic in C# using tuples and relational patterns

2 Feb 2022 1 mins C#

As I was writing bunch of ifs today, I was thinking whether it would be possible to use pattern matching from recent versions of C#. To make things more interesting, I was comparing multiple values and it was not a simple equality. Blindly typing the code, I was very surprised Roslyn didn’t complain.

Let’s jump into the code and be amazed.

string Foo(int x, int y)
{
    return (x, y) switch
    {
        (> 32, not 3) => "foo",
        (> 40, not > 4) => "bar",
    };
}

The (x, y) tuple is matched, nothing special. But then. Not a simple match on exact values. It’s using relational patterns. Wow, I was not expecting that to work. Nice!

This is going to be another special tool in my toolbox.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He's focused on data and business layers, language constructs, parallelism, databases and performance. He's Microsoft Most Valuable Professional and frequent speaker. You can read his articles, guides and tips and tricks at www.tabsoverspaces.com.