csharp / expert
Snippet
Algebraic Data Types via Generic Structs
While C# doesn't have native discriminated unions yet, generic readonly structs can emulate them to provide type-safe error handling. This 'Result' pattern forces the caller to acknowledge potential failure paths, reducing the reliance on exceptions for control flow. Using a struct avoids heap allocation, making it extremely efficient for high-throughput logic.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public readonly struct Result<T, TError>{private readonly T? _value;private readonly TError? _error;public bool IsSuccess { get; }private Result(T value) => (IsSuccess, _value, _error) = (true, value, default);private Result(TError error) => (IsSuccess, _value, _error) = (false, default, error);public static Result<T, TError> Success(T value) => new(value);public static Result<T, TError> Failure(TError error) => new(error);public TResult Match<TResult>(Func<T, TResult> onSuccess, Func<TError, TResult> onFailure) =>IsSuccess ? onSuccess(_value!) : onFailure(_error!);}
Breakdown
1
public readonly struct Result<T, TError>
Ensures immutability and zero-allocation on the heap when passed by value.
2
public TResult Match<TResult>(...)
Implements functional pattern matching, ensuring that both success and failure cases are handled.