csharp / intermediate
Snippet
Data Validation with Property Patterns
Property patterns allow you to match an object's properties against specific values or ranges directly within a switch expression. It provides a declarative way to handle complex conditional logic based on object state.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
public record User(string Name, int Age, bool IsActive);public string GetUserStatus(User user) => user switch{{ IsActive: false } => "Account Disabled",{ Age: < 18 } => "Minor Access",{ Name: "Admin" } => "Full Access",_ => "Standard User"};
Breakdown
1
{ IsActive: false } => "Account Disabled"
Matches if the IsActive property is specifically false.
2
{ Age: < 18 } => "Minor Access"
Uses a relational pattern to check if the Age property is less than 18.