csharp / intermediate
Snippet
Deep Inspection with Recursive Property Patterns
Property patterns allow you to match against the properties of an object. Recursive patterns go deeper, allowing you to check properties of nested objects directly within a single expression.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
public record Person(string Name, Address WorkAddress);public record Address(string City, string Country);public class PatternMatcher {public string CheckLocation(Person person) {return person switch {{ WorkAddress: { City: "Berlin" } } => "Works in Berlin",{ WorkAddress: { Country: "USA" } } => "Works in the United States",_ => "Unknown Location"};}}
Breakdown
1
{ WorkAddress: { City: "Berlin" } }
Matches if the nested WorkAddress object has a City property equal to 'Berlin'.
2
person switch { ... }
Uses a switch expression to return a value based on the matched pattern.