Skip to content

Results and Options

github-actions[bot] edited this page Nov 30, 2026 · 5 revisions

Results & Options (Ferrous.Results)

Result<T, TError> and Option<T> are allocation-free readonly struct types for making expected failures and missing values part of your method signatures—just like Rust's Result<T, E> and Option<T>.


Example: Order Checkout Pipeline

In vanilla .NET, expected domain failures (invalid coupon, out of stock, missing config) are typically thrown as exceptions or returned as null / (bool, T?) tuples. Exceptions allocate stack traces and hide failure modes from the method signature, while nullable returns lose why something failed and can be silently ignored:

// Vanilla C#: callers can't tell from the signature what can fail or why
public async Task<Receipt> CheckoutAsync(string rawCoupon, Guid itemId)
{
    Coupon? coupon = FindCoupon(rawCoupon);
    if (coupon is null)
        throw new InvalidOperationException("Invalid coupon");

    Inventory? item = await _inventory.TryReserveAsync(itemId);
    if (item is null)
        throw new InvalidOperationException("Out of stock");

    return await _billing.ChargeAsync(item, coupon);
}

With Ferrous.Results, domain errors become typed return values composed with AndThen, Map, AndThenAsync, or LINQ syntax—and FE0001 ([MustUse]) prevents callers from silently dropping a Result:

using Ferrous.Results;

public enum CheckoutError { InvalidCoupon, OutOfStock, PaymentDeclined }

public async Task<Result<Receipt, CheckoutError>> CheckoutAsync(string rawCoupon, Guid itemId)
{
    Option<Coupon> coupon = Option.FromNullable(FindCoupon(rawCoupon));

    Result<Coupon, CheckoutError> validCoupon = coupon
        .OkOr(CheckoutError.InvalidCoupon);

    return await validCoupon
        .AndThenAsync(c => ReserveAsync(itemId).MapAsync(item => (item, c)))
        .AndThenAsync(pair => ChargeAsync(pair.item, pair.c));
}

// Exhaustive handling at the HTTP boundary:
IResult response = (await CheckoutAsync(code, itemId)).Match(
    onOk: receipt => Results.Ok(receipt),
    onErr: err => err switch
    {
        CheckoutError.InvalidCoupon => Results.BadRequest("Invalid coupon"),
        CheckoutError.OutOfStock => Results.Conflict("Item out of stock"),
        CheckoutError.PaymentDeclined => Results.UnprocessableEntity("Payment declined"),
    });

Composing Multiple Results with LINQ Query Syntax

Result<Endpoint, string> endpoint =
    from host in ParseHost(rawHost)
    from port in ParsePort(rawPort)
    select new Endpoint(host, port);

Refined Value Types, CheckedMath, & Bounds-Safe .Get(...)

using Ferrous.Results;

// Overflow-safe generic math returning Option<T> or clamping
Option<int> sum = CheckedMath.CheckedAdd(int.MaxValue, 1); // None
int clamped = CheckedMath.SaturatingAdd(int.MaxValue, 1);  // int.MaxValue

// Refined non-empty / non-zero value types
Option<NonZero<int>> divisor = NonZero<int>.TryCreate(5);
Option<NonEmptyString> name = NonEmptyString.TryCreate("Ferrous");
Option<NonEmptyList<int>> items = NonEmptyList<int>.TryCreate([1, 2, 3]);

// Bounds-safe indexing returning Option<T> instead of throwing
int[] arr = [10, 20, 30];
Option<int> second = arr.Get(1);   // Some(20)
Option<int> missing = arr.Get(99); // None

anyhow-Style Error Context (ContextError & .WithContext(...))

Attach layered context to Result<T, TError> errors with zero allocations on the Ok path:

Result<Config, ContextError> config = ReadFile("appsettings.json")
    .WithContext("loading application configuration")
    .WithContext(() => $"bootstrapping node '{nodeId}'");

// On Err: "bootstrapping node 'n1': loading application configuration: file not found"

Async Railway Combinators & LINQ Comprehension

Chain multi-step sync and async Result/Option pipelines without nested if/TryGetOk boilerplate:

Result<OrderSummary, StoreError> summary = await FindAlbumAsync(id)
    .EnsureAsync(a => a.Stock >= qty, () => StoreError.OutOfStock(...))
    .BindAsync(a => PlaceOrderAsync(a, qty))
    .TapAsync(o => LogOrderAsync(o))
    .MapAsync(o => new OrderSummary(o.Id, o.TotalAmount));

// Or with async LINQ query comprehension:
Result<int, string> total = await (
    from a in FetchPriceAsync(id1)
    from b in FetchPriceAsync(id2)
    select a + b);

Benefits Over Vanilla .NET

Concern Vanilla .NET (throw, T?, (bool, T, E)) Result<T, TError> / Option<T>
Error visibility Hidden in XML docs or runtime stack traces Explicit in the return type
Performance throw captures stack trace & allocates on heap Stack-allocated readonly struct (0 heap allocations)
Ignored errors Silently compiled [MustUse] triggers FE0001 if a Result or Option is discarded
Uninitialized default Naive structs treat default as Ok(default) Sentinel state 0 (Uninitialized) + compile-time FE0404 error
NativeAOT JSON Custom converters required Built-in NativeAOT-safe ResultJsonConverter<T, TError> and OptionJsonConverter<T>
No hidden panics Easy to sneak throw or .Value in FE0401 flags .Unwrap()/.Expect(); FE0402 flags throw inside Result-returning methods

Clone this wiki locally