IC Improve Code Recipes

Recipe 5.5 · C#

A Result Type for Expected Failures

Problem

Some failures are part of normal business: insufficient funds, an expired coupon, a duplicate registration. Throwing exceptions for them is slow under load, hides the possible outcomes from the method signature, and turns ordinary control flow into try/catch. Returning null or false loses the reason.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: the reason is lost, or smuggled out through a string.
public bool Withdraw(decimal amount, out string error)
{
    error = null;
    if (amount > Balance)
    {
        error = "Insufficient funds";
        return false;
    }
    Balance -= amount;
    return true;
}

The improved recipe

A small Result<T> carries either a value or an Error with a code and message. Implicit conversions keep call sites short.

C#
using System;

namespace ImproveCode.Errors;

public sealed record Error(string Code, string Message)
{
    public static readonly Error None = new(string.Empty, string.Empty);
}

public sealed class Result<T>
{
    private readonly T? _value;

    private Result(T value)
    {
        _value = value;
        IsSuccess = true;
        Error = Error.None;
    }

    private Result(Error error)
    {
        ArgumentNullException.ThrowIfNull(error);
        IsSuccess = false;
        Error = error;
    }

    public bool IsSuccess { get; }

    public bool IsFailure => !IsSuccess;

    public Error Error { get; }

    public T Value => IsSuccess
        ? _value!
        : throw new InvalidOperationException(
            $"Cannot read Value of a failed result ({Error.Code}).");

    public static Result<T> Success(T value) => new(value);

    public static Result<T> Failure(Error error) => new(error);

    public static implicit operator Result<T>(T value) =>
        Success(value);

    public static implicit operator Result<T>(Error error) =>
        Failure(error);

    public TOut Match<TOut>(
        Func<T, TOut> onSuccess, Func<Error, TOut> onFailure) =>
        IsSuccess ? onSuccess(_value!) : onFailure(Error);
}

A domain class that uses it, and an extension that turns a result into an HTTP response:

C#
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;

namespace ImproveCode.Errors;

public static class AccountErrors
{
    public static readonly Error InsufficientFunds = new(
        "insufficient_funds", "The balance is too low.");

    public static readonly Error InvalidAmount = new(
        "invalid_amount", "The amount must be greater than zero.");
}

public sealed class Account(decimal openingBalance)
{
    public decimal Balance { get; private set; } = openingBalance;

    public Result<decimal> Withdraw(decimal amount)
    {
        if (amount <= 0)
        {
            return AccountErrors.InvalidAmount;
        }

        if (amount > Balance)
        {
            return AccountErrors.InsufficientFunds;
        }

        Balance -= amount;
        return Balance; // new balance
    }
}

public static class ResultHttpExtensions
{
    public static IResult ToHttpResult<T>(this Result<T> result) =>
        result.Match(
            value => Results.Ok(value),
            error => Results.Problem(
                statusCode: StatusCodes.Status422UnprocessableEntity,
                title: error.Message,
                extensions: new Dictionary<string, object?>
                {
                    ["errorCode"] = error.Code
                }));
}

Usage in a minimal API endpoint:

C#
app.MapPost("/accounts/{id}/withdraw",
    (int id, decimal amount, AccountStore store) =>
        store.Get(id).Withdraw(amount).ToHttpResult());

How it works

The return type now tells the truth: Withdraw can succeed with a new balance or fail with one of the listed errors. A caller has to look at IsSuccess (or call Match) to get the value, and reading Value on a failure throws, so a forgotten check is loud rather than silently wrong.

The implicit conversions let the method return AccountErrors.InsufficientFunds; or return Balance; without ceremony. The errors are static instances with stable codes, which makes them easy to test (Assert.Equal(AccountErrors.InsufficientFunds, result.Error)) and easy to document for API clients. Because Error is a record, equality compares code and message.

Match forces both branches to be handled and is how the result leaves the domain. The HTTP extension maps every failure to a 422 ProblemDetails with the same errorCode field the global handler in Recipe 5.4 uses, so clients see one error shape whether the failure came from a Result or an exception.

My rule for choosing: if the caller is expected to handle the failure as part of normal flow, use a Result. If the failure means something is broken (database down, bug, misconfiguration), throw. Exceptions remain the right tool for the unexpected.

Variations and pitfalls

  • Add a non-generic Result for operations with no return value, using the same shape.
  • Don't wrap every method in Result. Using it for code that cannot fail in an expected way adds noise and teaches people to ignore it.
  • If T is itself Error or object, the implicit conversions become ambiguous. Use Success(...) and Failure(...) explicitly in that case.
  • Libraries such as FluentResults, ErrorOr and OneOf offer richer versions with chaining (Bind, Map) and multiple errors. They are fine choices; the version here is small enough to own and explain to a new team member in five minutes.
  • Don't mix styles inside one operation. A method that returns a Result and also throws for the same kind of failure makes callers handle both.