csharp / intermediate
Snippet
Object Evaluation with Switch Patterns
Switch expressions combined with property patterns provide a concise and readable way to evaluate object states and return specific values.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
public record User(string Name, int Rank, bool IsActive);string GetAccessLevel(User user) => user switch{{ IsActive: false } => "No Access",{ Rank: > 10 } => "Admin",{ Rank: > 5 } => "Moderator",_ => "Standard User"};
Breakdown
1
user switch { ... }
Starts the switch expression to evaluate the user object.
2
{ IsActive: false } => "No Access"
Pattern matching that checks the IsActive property specifically.