Concept Flow - Property patterns
Start with an object
Check property values
Match pattern?
Execute true
End
Property patterns check if an object's properties match specified values, then decide the flow based on the match.
record Person(string Name, int Age); var person = new Person("Alice", 30); if (person is { Name: "Alice", Age: 30 }) Console.WriteLine("Match found"); else Console.WriteLine("No match");
| Step | Expression Evaluated | Property Checked | Value Found | Condition Result | Branch Taken | Output |
|---|---|---|---|---|---|---|
| 1 | person is { Name: "Alice", Age: 30 } | Name | "Alice" | Matches | Continue | |
| 2 | person is { Name: "Alice", Age: 30 } | Age | 30 | Matches | Continue | |
| 3 | if condition | N/A | N/A | True | True branch | Match found |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| person.Name | "Alice" | "Alice" | "Alice" | "Alice" |
| person.Age | 30 | 30 | 30 | 30 |
Property patterns check if an object's properties match given values.
Syntax: obj is { Prop1: val1, Prop2: val2 }
All specified properties must match for true.
Used in if, switch, or expressions.
Simplifies checking multiple properties at once.property patterns in C#?switch expression for an object person with a property Age?{ Age: > 18 }.record Person(string Name, int Age);
Person p = new("Alice", 25);
string result = p switch
{
{ Age: < 18 } => "Minor",
{ Age: >= 18 and < 65 } => "Adult",
_ => "Senior"
};
Console.WriteLine(result);record Product(string Name, decimal Price);
Product p = new("Book", 15.99m);
if (p is { Price > 10 })
{
Console.WriteLine("Expensive");
}{ Price: > 10 }.{ Price > 10 } which is invalid syntax.Person objects, how can you use property patterns in a switch expression to classify each person as "Child" if Age < 13, "Teen" if Age between 13 and 19, "Adult" if Age between 20 and 64, and "Senior" otherwise? Which code snippet correctly implements this?{ Age: < 13 } and combine with and for ranges.Pass the test and this pattern moves unknown