0 day streak
csharp / expert
Snippet

Functional Error Handling via Result Monads

Expert C# developers avoid throwing exceptions for expected failures. By using a Result record struct with a Bind (flatMap) method, you create a functional pipeline that handles errors as data, improving performance and predictability.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public readonly record struct Result<T> {
public T? Value { get; }
public string? Error { get; }
public bool IsSuccess { get; }
private Result(T? value, string? error, bool success) =>
(Value, Error, IsSuccess) = (value, error, success);
public static Result<T> Success(T value) => new(value, null, true);
public static Result<T> Failure(string error) => new(default, error, false);
public Result<U> Bind<U>(Func<T, Result<U>> next) =>
IsSuccess ? next(Value!) : Result<U>.Failure(Error!);
}
Breakdown
1
public readonly record struct Result<T>
Uses a readonly record struct for zero-allocation potential and value-based semantics.
2
public Result<U> Bind<U>(Func<T, Result<U>> next)
Implements the monadic 'bind' operation to chain operations while propagating failures automatically.