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.

Top comments (0)