Extended Property Patterns in C# 10
Khalid BOURZAYQ
Posted on February 2, 2022
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;
}
}
}
As you can see in our GetDiscount method, the syntax for accessing the address nested property is verbose
if (customer is { FullAddress : { City: "NYC" } })
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" })
That's it, for more details about the Extended property patterns
you can refer to the link below:
Extended property patterns
Posted on February 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 17, 2023