Earlier pattern matching could test types and extract values, but checking properties required additional if statements or nested conditions. This made working with object properties in pattern matching verbose and less readable.
C# 8.0 introduces property patterns using the { } syntax, allowing you to match against one or more properties of an object directly within the pattern. This enables concise, declarative code when working with object structures.
Code
csharp
public decimal CalculateShipping(Order order) => order switch
{
{ Destination: "UK" } => 5.99m,
{ Destination: "US", Express: true } => 15.99m,
{ Destination: "US" } => 8.99m,
_ => 20.00m
};
public bool IsEligible(Person person) => person switch
{
{ HasLicense: true } p when p.Age >= 18 => true,
{ HasPermit: true } p when p.Age >= 16 => true,
_ => false
};
public string Categorize(Product product) => product switch
{
{ InStock: false } => "Out of stock",
{ Category: "Electronics", IsPremium: true } => "Premium electronics",
_ => "Regular item"
};csharp
public decimal CalculateShipping(Order order)
{
if (order.Destination == "UK")
return 5.99m;
if (order.Destination == "US" && order.Express)
return 15.99m;
if (order.Destination == "US")
return 8.99m;
return 20.00m;
}
public bool IsEligible(Person person)
{
if (person.Age >= 18 && person.HasLicense)
return true;
if (person.Age >= 16 && person.HasPermit)
return true;
return false;
}
public string Categorize(Product product)
{
if (!product.InStock)
return "Out of stock";
if (product.Category == "Electronics" && product.IsPremium)
return "Premium electronics";
return "Regular item";
}Notes
- Use curly braces
{ PropertyName: pattern }to match against properties - Multiple properties can be matched in a single pattern:
{ Prop1: value1, Prop2: value2 } - Can be combined with type patterns:
obj is Person { HasLicense: true } - Use a
whenclause for comparisons; relational patterns such as{ Age: >= 18 }arrived with pattern matching improvements C# 9.0 - Property patterns can be nested to match against properties of nested objects
- Works with both switch expressions and is expressions