csharp / intermediate
Snippet
Complex State Evaluation via Nested Property Patterns
Property patterns allow you to match the properties of an object against specific values or ranges. By nesting them, you can inspect deep object hierarchies cleanly within a switch expression, avoiding cumbersome nested if-statements and improving readability.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
public record User(string Name, int Age, bool IsActive);public record Session(User User, bool IsExpired);string GetAccessStatus(Session session) => session switch{{ IsExpired: true } => "Session Expired",{ User: { IsActive: false } } => "User Inactive",{ User: { Age: < 18 } } => "Restricted Content",{ User: { Name: "Admin" } } => "Full Access",_ => "Standard Access"};
Breakdown
1
{ User: { IsActive: false } } => "User Inactive",
Matches if the 'User' property of the session has an 'IsActive' property equal to false.
2
{ User: { Age: < 18 } } => "Restricted Content",
Uses a relational pattern (<) within a property pattern to check a numeric range.