Result pattern in C#: when it beats exceptions
The result pattern in C# puts expected failure in the signature. A returned rejection ran about 160 times faster than a throw, which is rarely the best reason.
A gift card API that throws InsufficientBalanceException records a routine decline with the same
fail: log entry and stack trace it would give a crashed database. Customers try to spend more than a
card holds every day, so on-call engineers learn to skip that line, along with whichever real fault
arrives next to it. Every caller also needs a catch for a type that its signature never mentions.
The result pattern moves that decline into the return type: an operation returns a value describing what happened, and the "no" outcomes are ordinary values. Failures nobody nearby can act on should still unwind as exceptions, because applying results to every failure produces a different mess.
Severity is a poor test. A better one asks whether the immediate caller has a sensible next step. A missing file is a normal outcome when a user typed the path, and a startup failure when the application shipped with it.
Other ecosystems draw the same line. Rust has Result for recoverable errors and panic! for
unrecoverable ones, which it describes as
symptoms of bugs. Microsoft's exception best practices
give the .NET version: use exception handling for events that are truly exceptional, and check for
conditions that happen routinely. int.TryParse has been a two-outcome result since long before anyone
called it a pattern.
Which failures belong in the return type
Expected failure, returned
Card expired or balance too low. The caller has a branch for it and the signature shows it.
Expected failure, thrown
A routine decline fills the error dashboard, and every caller needs a catch that nothing in the signature mentions.
Unexpected failure, returned
A "database down" error travels up through code that cannot act on it and has no stack trace when it arrives.
Unexpected failure, thrown
Database gone or a bug. It unwinds to the request boundary, which rolls back, logs the stack and answers 500.
The common first attempt is a class with bool IsSuccess, T? Value and string? Error. It allows
combinations that mean nothing, such as success with an error, and it lets a caller read Value without
checking anything. A closed set of outcome types has neither problem:
public abstract record RedeemResult
{
private RedeemResult() { }
public sealed record Redeemed(decimal Remaining) : RedeemResult;
public sealed record InsufficientBalance(decimal Available) : RedeemResult;
public sealed record Expired(DateOnly On) : RedeemResult;
}
public sealed class GiftCard(decimal balance, DateOnly expiresOn)
{
public decimal Balance { get; private set; } = balance;
public RedeemResult Redeem(decimal amount, DateOnly today)
{
// A non-positive amount past validation is a bug, so it still throws.
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
if (today > expiresOn) return new RedeemResult.Expired(expiresOn);
if (amount > Balance) return new RedeemResult.InsufficientBalance(Balance);
Balance -= amount;
return new RedeemResult.Redeemed(Balance);
}
}The private constructor blocks ordinary derivation: a plain record Sneaky : RedeemResult; elsewhere fails
with CS7036. It is a convention rather than a seal, though, because the compiler also synthesizes a
protected copy constructor, and a record in another assembly can derive by calling base(seed). That
compiled and ran on .NET 10. Each case carries exactly the data that makes sense for it, so Available
cannot exist on a success, and a caller can branch on types without comparing messages.
The boundary then maps each case to a response, using problem details for the rejections:
return card.Redeem(body.Amount, today) switch
{
RedeemResult.Redeemed r => Results.Ok(new { remaining = r.Remaining }),
RedeemResult.InsufficientBalance i => Results.Problem(
statusCode: StatusCodes.Status409Conflict,
title: "Insufficient balance",
type: "https://example.com/problems/insufficient-balance",
extensions: new Dictionary<string, object?> { ["available"] = i.Available }),
RedeemResult.Expired e => Results.Problem(
statusCode: StatusCodes.Status410Gone,
title: "Card expired",
type: "https://example.com/problems/card-expired",
extensions: new Dictionary<string, object?> { ["expiredOn"] = e.On }),
_ => throw new UnreachableException(),
};Requesting 40.00 from a card holding 25.00 returned this:
HTTP/1.1 409 Conflict
Content-Type: application/problem+json
{"type":"https://example.com/problems/insufficient-balance","title":"Insufficient balance","status":409,"available":25.00}That discard arm is a real weakness on .NET 10. The compiler does not treat the private constructor as
closing the hierarchy, so leaving it out produces warning CS8509 even with every case handled, and
keeping it means a new outcome added later compiles without complaint and fails at runtime.
C# 15 adds a closed modifier
and union types aimed at exactly this. Compiling with public closed record RedeemResult on the .NET
11 release candidate, the discard can go, and removing the Expired arm produces CS8509 naming the
missing case. It also closes the copy-constructor gap: the same forged record in another assembly fails
with CS9382. The linked page still described the .NET 11 SDK as prerelease when this was written.
One operation returning a result is pleasant. Several in a row is where the cost appears, because C#
has no equivalent of Rust's ? operator. You either write an early-return if after every call or
add a combinator:
public abstract record Result<T, TError>
{
private Result() { }
public sealed record Ok(T Value) : Result<T, TError>;
public sealed record Err(TError Error) : Result<T, TError>;
public Result<TNext, TError> Then<TNext>(Func<T, Result<TNext, TError>> next) => this switch
{
Ok ok => next(ok.Value),
Err err => new Result<TNext, TError>.Err(err.Error),
_ => throw new UnreachableException(),
};
}
public Result<Receipt, RedeemError> Redeem(string rawCode, decimal amount) =>
ParseCode(rawCode)
.Then(FindCard)
.Then(card => Charge(card, amount));It reads well, and the costs sit around it. Every step has to share one TError, so RedeemError
grows to cover failures from all three steps, or each layer maps errors into its own type. Async steps
need a second family of overloads over Task<Result<...>>. Stack traces fill with lambdas. And the
signature change spreads: when a deep method starts returning a result, every method above it must
handle or forward it. An exception crosses those same layers with no code in between.
So keep results close to the decision. They work best one or two calls away from something that can act on them, usually a domain operation and its endpoint or use case. Threading a result through six layers of forwarding code is a sign that those layers have nothing to contribute to the failure, and an exception would have crossed them with no code at all.
Infrastructure faults. A connection failure usually has no useful handling in a domain method.
Returning Result.Fail("db down") adds a failure case to every signature that no caller can act on, and
it discards the stack trace you need most. Let it throw, including OperationCanceledException, and handle it at
the request boundary. If one specific caller can act on a specific fault, catch it there.
Unit-of-work helpers. This one bites during migration from exceptions. A helper that commits when its callback returns normally relied on the throw to roll back. A demo that writes an audit row and then rejects the operation shows what changes:
rows after thrown rejection: 0
Declined { Available = 12.50 } rows after returned rejection: 1
Declined { Available = 12.50 } rows with commit check: 0The returned rejection committed the partial write, because to the helper it looked like success. Either
do all writes after the decision or make the helper ask the result whether to commit. That third line is
the same work with a shouldCommit check added.
Discarded results. card.Redeem(1000m, today); as a bare statement compiles with no warning and does
nothing, and the caller carries on as if the money moved. A thrown exception cannot be ignored by
forgetting about it, so this failure mode is new. Code review and analyzers have to cover it, and names
like Redeem make the mistake easy to miss.
Exceptions are slower, and it is worth knowing by how much before using that as your argument. This BenchmarkDotNet run rejects one operation at two call depths on .NET 10 and a Ryzen 9 9950X3D. Its ratio standard deviation was 21 to 23, so read the ratios as two orders of magnitude:
| Rejection path | Depth | Mean | Allocated |
|---|---|---|---|
| Return a result | 1 | 8.4 ns | 32 B |
| Throw and catch | 1 | 1,388 ns | 336 B |
| Return a result | 8 | 19 ns | 32 B |
| Throw and catch | 8 | 3,832 ns | 1,352 B |
That is roughly 160 to 200 times slower, and it is also about 4 microseconds. At 1,000 rejections per second, 3.8 microseconds each comes to 3.8 milliseconds of CPU per second, under 0.4% of one core. Logging each exception would add to that, and this benchmark did not measure logging.
A rejection cost 8 ns returned and 1,388 ns thrown at depth 1. Off the hot path, the stronger reason to return it is a signature that shows the failure.
Walk a single request through the rule. Malformed JSON never reaches your code, because the framework answers 400. An expired card and a low balance are results, since the endpoint has a planned response for each. A negative amount that survived validation is a bug, so it throws. A database timeout has no meaningful handling at this level, so it throws and the boundary rolls back and returns 500.
The half-finished migration is the version of this that reviews miss: a result type added beside the old throw, with callers still catching. That refactor is among the Design Principles exercises, and the grader keeps the rules red while the old exception path survives.
Practice what you just read
- Open in the editor: Make Failure a Result
Design principles Medium Free, no account needed
Make Failure a Result
EnrollmentService throws for an expected full-course decision, forcing every caller to catch normal control flow. Return a sealed immutable EnrollmentResult, and do not leave an unused result beside the old exception path.
More like this: SOLID principles exercises →