0 day streak
csharp / expert
Snippet

Exhaustive Pattern Matching for Domain Logic

Leveraging recursive patterns and guard clauses allows for declarative, type-safe control flow. This pattern emulates functional programming 'match' expressions, ensuring all possible data shapes are handled explicitly at the function level.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
public record ProcessingState;
public record Idle : ProcessingState;
public record Working(int Progress) : ProcessingState;
public record Faulted(string Error) : ProcessingState;
public static string Describe(ProcessingState state) => state switch
{
Idle => "System is dormant",
Working { Progress: > 90 } => "Almost finished...",
Working w => $"Processing: {w.Progress}%",
Faulted(var msg) => $"Critical Failure: {msg}",
_ => throw new ArgumentException("Unknown state", nameof(state))
};
Breakdown
1
Working { Progress: > 90 }
A property pattern with a relational sub-pattern to filter specific object states.
2
Faulted(var msg)
Positional deconstruction of a record to extract internal state directly.