DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Extended Property Patterns With Switch

Let’s explore Extended Property Patterns, introduced in C# 10, which allow combining more complex conditions on object properties during pattern matching. See the example in the code below.

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class Program
{
    public static void Main()
    {
        Product product = new Product { Name = "Pen", Price = 5.99m };

        string result = product switch
        {
            { Price: > 10.00m } => "Expensive product",
            { Price: <= 10.00m } => "Affordable product",
            _ => "Price unknown"
        };

        Console.WriteLine(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
With Extended Property Patterns, you can use pattern matching to access nested properties of an object and apply conditions directly to those properties. This simplifies the checking of complex conditions on objects and makes the code more readable and expressive. In the example above, we use this feature to check if a Product object has a Price greater than a specific value, all within a single switch expression.

Source code: GitHub

I hope this tip helps you use Extended Property Patterns to write more expressive and efficient code! Until next time.

Top comments (0)