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
C#
public decimal CalculateShipping(Order order) => order switch
{
{ Total: > 100 } => 0m,
{ Destination: "UK" } => 5.99m,
{ Destination: "US", Weight: < 1.0 } => 8.99m,
{ Destination: "US" } => 15.99m,
_ => 20.00m
};
public bool IsEligible(Person person) => person switch
{
{ Age: >= 18, HasLicense: true } => true,
{ Age: >= 16, HasPermit: true } => true,
_ => false
};
public string Categorize(Product product) => product switch
{
{ Price: < 10, Stock: > 100 } => "Cheap and plentiful",
{ Price: > 1000, Category: "Electronics" } => "Premium electronics",
{ InStock: false } => "Out of stock",
_ => "Regular item"
};
C#
public decimal CalculateShipping(Order order)
{
if (order.Total > 100)
return 0m;
if (order.Destination == "UK")
return 5.99m;
if (order.Destination == "US" && order.Weight < 1.0)
return 8.99m;
if (order.Destination == "US")
return 15.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.Price < 10 && product.Stock > 100)
return "Cheap and plentiful";
if (product.Price > 1000 && product.Category == "Electronics")
return "Premium electronics";
if (!product.InStock)
return "Out of stock";
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 }
- Supports relational patterns (
>
,<
,>=
,<=
) for numeric comparisons - Can be combined with type patterns:
obj is Person { Age: >= 18 }
- Property patterns can be nested to match against properties of nested objects
- Works with both switch expressions and is expressions