C# 9 Pattern Matching: The Definitive Guide

C# 9 enhanced pattern matching significantly. We can now write more expressive and “functional” logic.

Logical Patterns

if (c is >= 'a' and <= 'z' or >= 'A' and <= 'Z')
{
    // It's a letter
}

if (obj is not null) // Readable null check!
{
    // ...
}

Switch Expressions

string waterState = tempInF switch
{
    (> 32) and (< 212) => "liquid",
    < 32 => "solid",
    > 212 => "gas",
    _ => "transition"
};

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.