Tuesday Coding Tip 14 — Pattern matching in C#

2 5 29
calendar_todayschedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Since C# 7, you can use pattern matching to write simple and safer code. First, it allows you to return a value from a switch expression, saving you the hassle of creating a temporary on a separate line.

public enum State {
    None, Foo, Bar
}

public void PrintState(State state)
{
    // Original switch
    switch (state)
    {
        case State.Foo:
            Console.WriteLine("Foo"); break;
        case State.Bar:
            Console.WriteLine("Bar"); break;
        default:
            Console.WriteLine("None"); break;
    }

    // Rewritten switch
    Console.WriteLine(state switch {
        State.Foo => "Foo",
        State.Bar => "Bar",
        _ => "None"
    });
}

Second, it can match not only on discrete values but expressions as well and the compiler can warn you if some expression is redundant (relational patterns).

public static string SubjectiveTemp(int degrees)
{
    // Relation patterns were added in C# 9
    return degrees switch
    {
        -273 => "Absolute zero",
        >-273 and <-10 => "Freezing cold",
        >-10 and <10 => "Cold",
        >10 and <25 => "Livable",
        _ => "HOT!"
    };
}

Third, it can match on more than one value through records, lists, etc. As a cherry on top, pattern matching also encapsulates type and null matching.

public static void CustomPrint<T>(T? value)
{
    if (value is int)
        Console.WriteLine($"int: {value}");
    else if (value is string)
        Console.WriteLine($"string: {value}");
    else if (value is null)
        Console.WriteLine($"null");
    else
        Console.WriteLine("unknown");
}

Note that when pattern matching, the _ symbol is the discard pattern, matching everything that reaches it. Also, switches do not by default warn the user if they forget a branch (usually with enums). Pattern matching does detect and warns on such occasions.

More on pattern matching: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching

Part 2 of 3 in Tuesday Coding Tips

2 Comments

0 votes
2
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelski - Apr 23

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelski - Apr 9
chevron_left
847 Points37 Badges
Brno, Czech Republiclinkedin.com/in/jakub-neruda
19Posts
10Comments
9Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!