ZetCode

C# Result and Option types

last modified November 15, 2026

This article shows how to model absence and failure with Option<T> and Result<T> in C#. We implement both as readonly structs, handle them with Match, chain operations with Map and Bind, and compare the approach with exceptions and the Try methods in the base class library.

An Option represents a value that may be absent. A Result represents an operation that either succeeded with a value or failed with a reason. Both make the possible outcomes part of the return type, so a caller has to deal with the failure case before using the value. The compiler does not enforce this as strictly as it does with a C# 15 union, but the shape of the type documents the contract and pattern matching keeps the handling in one place.

These types come from functional programming, where a function returns a value instead of throwing for an expected failure. They are most useful for operations that fail for ordinary reasons: parsing input, looking up a record, validating a form, or calling a service that may be unavailable. Exceptions remain the right tool for programming errors and truly exceptional conditions.

Option: a value that may be absent

Option<T> wraps a value or nothing. Compared with a nullable reference, it works for value types without boxing, and the Match method forces the caller to supply both branches. The struct stores a flag and a value, so it does not allocate.

Program.cs
var alice = FindUser(1);
var unknown = FindUser(42);

Console.WriteLine(alice.Match(u => u.Name, () => "not found"));
Console.WriteLine(unknown.Match(u => u.Name, () => "not found"));
Console.WriteLine(unknown.GetValueOrDefault(new User(0, "guest")).Name);

static Option<User> FindUser(int id) =>
    id == 1 ? Option.Some(new User(1, "Alice")) : Option.None<User>();

public sealed record User(int Id, string Name);

public readonly struct Option<T>
{
    private readonly T _value;

    private Option(T value)
    {
        _value = value;
        HasValue = true;
    }

    public bool HasValue { get; }

    public T Value => HasValue
        ? _value
        : throw new InvalidOperationException("Option has no value");

    public TResult Match<TResult>(Func<T, TResult> some, Func<TResult> none)
        => HasValue ? some(_value) : none();

    public T GetValueOrDefault(T fallback) => HasValue ? _value : fallback;

    public static Option<T> Some(T value) => new(value);

    public static Option<T> None => default;
}

public static class Option
{
    public static Option<T> Some<T>(T value) => Option<T>.Some(value);

    public static Option<T> None<T>() => Option<T>.None;
}

FindUser returns a value for id 1 and an empty option for any other id. The caller uses Match to turn both cases into a string, and GetValueOrDefault to supply a fallback user.

public TResult Match<TResult>(Func<T, TResult> some, Func<TResult> none)
    => HasValue ? some(_value) : none();

Match is the eliminator of the type: it takes the function to run when a value exists and the function to run when it does not, and returns whichever result they produce. Both branches must return the same type, so the caller cannot accidentally ignore the empty case. The static Option class provides a shorter syntax for the common generic arguments.

public T Value => HasValue
    ? _value
    : throw new InvalidOperationException("Option has no value");

Value is available for code that already checked HasValue, but reading it on an empty option throws. This is the same compromise as Nullable<T>.Value: the safe path is Match or GetValueOrDefault. The private constructor and the readonly field make an option immutable after creation.

$ dotnet run
Alice
not found
guest

Result: success or failure

Result<T> extends the idea with a reason for failure. The success case carries a value; the failure case carries an error message or an error object. Map transforms a successful value and leaves a failure untouched; Bind does the same for a function that itself returns a result. Together they form a pipeline that stops at the first failure.

Program.cs
var ok = Divide(10, 2);
var bad = Divide(10, 0);

Console.WriteLine(ok.Match(v => $"result: {v}", e => $"error: {e}"));
Console.WriteLine(bad.Match(v => $"result: {v}", e => $"error: {e}"));

var success = Parse("42").Bind(n => Divide(100, n)).Map(v => $"{v:F2}");
var failure = Parse("abc").Bind(n => Divide(100, n)).Map(v => $"{v:F2}");

Console.WriteLine(success.Match(v => v, e => e));
Console.WriteLine(failure.Match(v => v, e => e));

static Result<int> Parse(string text) =>
    int.TryParse(text, out int value)
        ? Result<int>.Success(value)
        : Result<int>.Failure($"'{text}' is not a number");

static Result<decimal> Divide(decimal a, decimal b) =>
    b == 0
        ? Result<decimal>.Failure("division by zero")
        : Result<decimal>.Success(a / b);

public readonly struct Result<T>
{
    private readonly T _value;
    private readonly string _error;

    private Result(T value, string error, bool isSuccess)
    {
        _value = value;
        _error = error;
        IsSuccess = isSuccess;
    }

    public bool IsSuccess { get; }

    public T Value => IsSuccess
        ? _value
        : throw new InvalidOperationException(_error);

    public string Error => IsSuccess ? string.Empty : _error;

    public TResult Match<TResult>(Func<T, TResult> success, Func<string, TResult> failure)
        => IsSuccess ? success(_value) : failure(_error);

    public Result<TResult> Map<TResult>(Func<T, TResult> map)
        => IsSuccess
            ? Result<TResult>.Success(map(_value))
            : Result<TResult>.Failure(_error);

    public Result<TResult> Bind<TResult>(Func<T, Result<TResult>> bind)
        => IsSuccess ? bind(_value) : Result<TResult>.Failure(_error);

    public static Result<T> Success(T value) => new(value, string.Empty, true);

    public static Result<T> Failure(string error) => new(default!, error, false);
}

Divide returns a result instead of throwing when the divisor is zero. The pipeline parses a string, divides 100 by the parsed number, and formats the value; a failure at any step skips the rest and keeps the first error message.

var success = Parse("42").Bind(n => Divide(100, n)).Map(v => $"{v:F2}");

Parse returns Result<int>, so the next step uses Bind, which expects a function that returns a result. Map is for a function that returns a plain value, such as the formatting lambda. The two methods differ only in whether the callback can produce a new failure. In the second pipeline, Parse("abc") fails, so Bind and Map return the same error without calling either lambda.

public Result<TResult> Bind<TResult>(Func<T, Result<TResult>> bind)
    => IsSuccess ? bind(_value) : Result<TResult>.Failure(_error);

Bind is also called SelectMany in LINQ and flatMap in functional languages. It flattens what would otherwise be a Result<Result<T>>. The default! in the failure factory gives the value field a value of the right type; the field is never read because Value checks IsSuccess first.

$ dotnet run
result: 5
error: division by zero
2.38
'abc' is not a number

Why not exceptions?

Exceptions are excellent for unexpected failures: a missing file, a broken connection, a bug that produced an invalid state. They are less convenient for outcomes that are part of normal operation. Every caller has to remember which exceptions a method throws, and a forgotten catch moves the failure far away from the call. A result type puts the failure in the signature, where it can be seen and handled.

There is also a cost difference. Throwing and catching an exception is expensive compared with returning a struct, so parsing a million user records with exceptions for invalid input is slow. Result types keep the failure path cheap. On the other hand, a result type adds a branch to every call site, and wrapping every method in Result<T> makes simple code noisy. Use it where failure is expected and where the caller can do something useful with the reason.

Results and the base class library

The .NET libraries already use result-shaped APIs in several places. int.TryParse returns a bool and writes the value to an out parameter; Dictionary.TryGetValue does the same for a lookup. Nullable<T> models absence for value types, and string? does it for reference types with the help of nullable annotations.

An Option<T> adds methods such as Match, Map, and Bind, which the Try pattern cannot express without repetitive if blocks. A Result<T> adds a reason, which a bool cannot carry. Both are small enough to include in a project instead of taking a dependency, and both work well with the pattern matching described in the pattern matching tutorial.

The pattern has limits. A struct result is copied on every call, so very large success values are better wrapped by reference. A single string error is enough for a demo but weak for an API; a real project usually makes the error a type of its own, or uses a generic Result<T, TError>. And a result type cannot replace exceptions for bugs: an invalid operation on an object that should never happen is still an exception, not a value to return.

Source

Nullable value types

Int32.TryParse

Pattern matching

In this article we have implemented Option and Result types in C#. See also the pattern matching, exception, generics, and record tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.