A Result type for C#: handling expected failures without exceptions
Exceptions are great at one thing: unwinding the stack when something has gone so wrong that the current operation cannot continue. They are terrible at describing outcomes you expect. A missing config value, a parse error in user input, a duplicate key on insert: none of these are exceptional, they are Tuesday. When every one of them is an exception, the method signature lies. int ParsePort(string raw) says it returns an int, and the documentation (if you are lucky) says it may throw.
Functional languages solve this with a type that makes the failure part of the return value. C# still has no discriminated unions, but a small Result type with a couple of combinators gets you most of the way there.
The type
public sealed record Error(string Code, string Message);
public sealed record Result<T>
{
private readonly T? _value;
private readonly Error? _error;
private Result(T value) { _value = value; }
private Result(Error error) { _error = error; }
public bool IsOk => _error is null;
public static Result<T> Ok(T value) => new(value);
public static Result<T> Fail(Error error) => new(error);
public TOut Match<TOut>(Func<T, TOut> ok, Func<Error, TOut> fail) =>
_error is null ? ok(_value!) : fail(_error);
}
Two things matter here. The constructors are private, so the only way to get a Result is through Ok or Fail, which means an instance is always in a valid state. And Match forces the caller to handle both cases, because there is no public Value to grab blindly.
Combinators
The type alone is not worth much; the combinators are what keep call sites flat.
public static class ResultExtensions
{
public static Result<TOut> Map<TIn, TOut>(this Result<TIn> source, Func<TIn, TOut> map) =>
source.Match(value => Result<TOut>.Ok(map(value)), Result<TOut>.Fail);
public static Result<TOut> Bind<TIn, TOut>(this Result<TIn> source, Func<TIn, Result<TOut>> bind) =>
source.Match(bind, Result<TOut>.Fail);
}
Map transforms a success value, Bind chains a step that can itself fail, and both pass an error through untouched. A chain short-circuits on the first failure, exactly like exceptions, but without unwinding anything:
static Result<int> ParsePort(string raw) =>
int.TryParse(raw, out var port) && port is > 0 and <= 65535
? Result<int>.Ok(port)
: Result<int>.Fail(new Error("port.invalid", $"'{raw}' is not a valid TCP port."));
static Result<int> CheckPortIsFree(int port) =>
CanBind(port) ? Result<int>.Ok(port)
: Result<int>.Fail(new Error("port.busy", $"Port {port} is already in use."));
var message = ParsePort(config["HealthPort"])
.Bind(CheckPortIsFree)
.Match(
port => $"Listening on {port}",
error => $"Config error [{error.Code}]: {error.Message}");
Every step stays at one level of indentation, and the error at the end carries the code of the step that failed. The old version of this code had three nested try blocks and a custom exception type that nobody caught.
The rule I try to follow
- Return an error when the caller can reasonably do something about it: bad input, missing data, a busy port, a declined payment.
- Throw when the only sane response is to crash and fix the code: a null argument in a place the contract forbids, an index out of range, a violated invariant.
In practice that means ArgumentException and its relatives stay, while most InvalidOperationException and every custom “NotFound” exception in a service layer become a Fail.
Caveats
For asynchronous code, Task<Result<T>> works fine and Bind lambdas can be async, but you will eventually want MapAsync and BindAsync overloads. Serialization of a Result across an API boundary is awkward; return a proper DTO and map at the edge. And if you want more than two cases (for instance a third Timeout outcome), the record-hierarchy approach starts to creak; that is the point to look at libraries such as ErrorOr, OneOf or LanguageExt, which have already solved it.
I keep coming back to the thirty-line version above anyway. It is easy to read in a code review, has no dependencies, and has removed more catch blocks from my codebases than any refactoring tool.