csharp / intermediate
Snippet
Advanced Property Pattern Matching
Property patterns allow you to match an object's properties against specific values or ranges. This is highly readable and replaces complex nested if-statements.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
public record User(string Name, int Age, bool IsAdmin);public string GetAccessLevel(User user) => user switch{{ IsAdmin: true } => "Full Access",{ Age: < 18 } => "Restricted Access",{ Name: "Guest" } => "Temporary Access",_ => "Standard Access"};
Breakdown
1
user switch { ... }
Starts a switch expression to evaluate the user object.
2
{ IsAdmin: true } => ...
Matches if the IsAdmin property is exactly true.
3
{ Age: < 18 } => ...
Uses a relational pattern to check if Age is less than 18.