DEV Community

Cover image for C# - Pattern Matching Enhancements
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Pattern Matching Enhancements

Pattern matching in C# has been significantly enhanced in recent versions, providing more expressive and concise ways to perform data queries. You can use switch expressions to simplify complex conditional logic. Further extended pattern-matching capabilities, allowing for more patterns like relational, logical, and parenthesized patterns.

Here's an example that demonstrates the use of various pattern-matching enhancements:

public class WeatherForecast
{
    public decimal TemperatureCelsius { get; init; }
    public string Summary { get; init; }
}

public static string GetForecastMessage(WeatherForecast forecast) =>
    forecast switch
    {
        // Relational pattern
        { TemperatureCelsius: >= 30.0m } => "Stay cool, it's hot out there!",

        // Logical pattern
        { TemperatureCelsius: < 0 and >= -10 } => "It's cold, but manageable.",

        // Combination of property and relational patterns
        { TemperatureCelsius: < -10, Summary: "Snowing" } => "Bundle up, heavy snow!",

        // Parenthesized pattern
        { TemperatureCelsius: (< 20 and > 10) } => "It's a nice day with moderate temperature.",

        // Discard pattern
        _ => "Weather is unpredictable."
    };

public static void Main(string[] args)
{
    var forecast = new WeatherForecast { TemperatureCelsius = 25.0m, Summary = "Sunny" };
    Console.WriteLine(GetForecastMessage(forecast));
}
Enter fullscreen mode Exit fullscreen mode

Use pattern matching to write more readable and maintainable conditional logic. It reduces the amount of code and increases clarity compared to traditional if-else statements.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay