DEV Community

Khalid BOURZAYQ
Khalid BOURZAYQ

Posted on • Updated on

Extended Property Patterns in C# 10

What does it mean?

Basically, in C# 8.0 Microsoft has introduced the new pattern: Property pattern.

A property pattern matches an expression when an expression result is not null and every nested pattern matches the corresponding property or field of the expression result.

In C# 10, you can reference nested properties or fields within a property pattern.

Example

The following code sample shows a C# Customer class , which contains some properties and a nested property named Address which is in itself an object.


    public class Customer
    {
        public string Name { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }

    }
    public class Address
    {
        public string City { get; set; }
        public string ZipCode { get; set; }

    }

    public class DiscountCalculator
    {
        public double GetDiscount(Customer customer)
        {
            if (customer is { Address : { City: "NYC" } })
            {
                return 0.8;
            }
            else
            {
                return 0.9;
            }
        }
    }

Enter fullscreen mode Exit fullscreen mode

As you can see in our GetDiscount method, the syntax for accessing the address nested property is verbose


 if (customer is { FullAddress : { City: "NYC" } })

Enter fullscreen mode Exit fullscreen mode

In C# 10, it’s much more practical, you can reference nested properties or fields within a property pattern.


if (customer is { FullAddress.City: "NYC" })

Enter fullscreen mode Exit fullscreen mode

That's it, for more details about the Extended property patterns
you can refer to the link below:
Extended property patterns

Top comments (0)