0 day streak
csharp / expert
Snippet

Exhaustive Nested Pattern Guards

Modern C# control flow leverages pattern matching to handle complex state evaluations in a declarative manner. Property patterns and relational patterns (like `> 5`) allow for expressive logic that is more readable and less error-prone than nested `if-else` blocks, while the `switch` expression ensures exhaustive handling.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public record User(string Role, bool IsActive, int AccessLevel);
public class AuthProcessor
{
public string EvaluateAccess(User user) => user switch
{
{ Role: "Admin", IsActive: true } => "Full Access",
{ Role: "Editor", AccessLevel: > 5 } => "Restricted Edit",
{ Role: var r, IsActive: false } => $"Suspended {r}",
_ => "Access Denied"
};
public static bool IsComplexMatch(object obj) => obj switch
{
int[] { Length: > 0 } arr when arr[0] > 100 => true,
string s or (int or long) => true,
_ => false
};
}
Breakdown
1
{ Role: "Editor", AccessLevel: > 5 }
Combines a property pattern with a relational pattern to match specific object states.
2
int[] { Length: > 0 } arr when arr[0] > 100
A positional pattern combined with a 'when' guard to perform deep inspection of array contents.