# C# Union Types vs the Result Pattern: Performance

> I benchmarked four return types for a command handler on .NET 11: the Result class, a union of records, a generic union, and a hand-written non-boxing union. Every union beat the Result class without async, and behind an async handler the Task allocation outweighed all four.

Published: 2026-11-21. Author: Milan Jovanović.

Canonical: https://milanjovanovic.tech/blog/csharp-union-types-performance

On .NET 11, returning a **C# 15 union** and matching it with a `switch` took 2 to 5 ns in my benchmark, against 5 to 8 ns for a **Result** class.
A union is a struct, so there's no wrapper object to allocate, but its constructor boxes value-type cases such as a `Guid`.
Behind an `async` handler, the `Task` allocation outweighed every return type.

I compared the two designs in [**Can C# 15 Union Types Replace the Result Pattern?**](https://milanjovanovic.tech/blog/csharp-union-types-vs-result-pattern).
That issue is about what the compiler catches.
This article is about what each one costs at runtime.

## The Four Return Types

All four return the same outcome: a `Guid` on success, or an overlap failure.

The **Result class** is the one from my [**Result pattern**](https://milanjovanovic.tech/blog/functional-error-handling-in-dotnet-with-the-result-pattern) article, trimmed here to its shape:

```csharp
public sealed record Error(string Code, string Description);

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

    public TValue Value => IsSuccess
        ? _value!
        : throw new InvalidOperationException("A failure result has no value.");

    public static implicit operator Result<TValue>(TValue value) => Success(value);
}
```

The **union of records** has one record per outcome:

```csharp
public sealed record BookingReserved(Guid BookingId);
public sealed record ApartmentNotFound(Guid ApartmentId);
public sealed record Overlap(DateOnly Start, DateOnly End);

public union ReserveBookingResult(BookingReserved, ApartmentNotFound, Overlap);
```

The **generic union** has the same shape as `Result<T>`:

```csharp
public union Result<T>(T, Error);
```

The **custom union** is a struct with the `[Union]` attribute.
It keeps the value in a typed field and has one `TryGetValue` method per case:

```csharp
[Union]
public readonly struct ValueResult<T> : IUnion
{
    private readonly T _value;
    private readonly Error? _error;
    private readonly bool _isValue;

    public ValueResult(T value)
    {
        _value = value;
        _error = null;
        _isValue = true;
    }

    public ValueResult(Error error)
    {
        _value = default!;
        _error = error;
        _isValue = false;
    }

    public object? Value => _isValue ? _value : _error;

    public bool HasValue => _isValue || _error is not null;

    public bool TryGetValue(out T value)
    {
        value = _value;
        return _isValue;
    }

    public bool TryGetValue(out Error value)
    {
        value = _error!;
        return !_isValue && _error is not null;
    }
}
```

## What the Compiler Generates

I disassembled the Release build to see where each version allocates.
Here's the IL for the generic union, with namespaces trimmed:

```cil
.class public sequential sealed Result`1 extends System.ValueType
    implements System.Runtime.CompilerServices.IUnion
  .field initonly object '<Value>k__BackingField'

  .method void .ctor(!0)
  {
    IL_0000: ldarg.0
    IL_0001: ldarg.1
    IL_0002: box !0
    IL_0007: stfld object Result<!0>::<Value>k__BackingField
    IL_000c: ret
  }

  .method void .ctor(Error)
  {
    IL_0000: ldarg.0
    IL_0001: ldarg.1
    IL_0002: stfld object Result<!0>::<Value>k__BackingField
    IL_0007: ret
  }
```

The union is a struct with one `object` field and one constructor per case.
The `T` constructor has a `box` instruction, so every `Result<Guid>` success puts the `Guid` on the heap.
The `Error` constructor stores the reference as it is.
`ReserveBookingResult` has the same shape, and each of its three constructors is a plain `stfld` with no `box`, because a record is already a reference.

Returning the union doesn't allocate anything else:

```cil
// HandleGenericUnion: return Id;
IL_000e: ldsfld System.Guid ReturnAndMatch::Id
IL_0013: newobj void Result<System.Guid>::.ctor(!0)
IL_0018: ret
```

`newobj` on a struct builds it in place, without a heap allocation.
The only allocation is the `box` inside the constructor.
The Result class version calls `Result<Guid>::op_Implicit` instead, which creates a new `Result<Guid>` object, and `Result.Failure<Guid>` does the same for a failure.

A `switch` over a compiler-generated union reads `Value` and tests the object with `isinst`, one case at a time:

```cil
// GenericUnion: HandleGenericUnion(Succeeds) switch { Guid => 201, Error ... }
IL_000e: call object Result<System.Guid>::get_Value()
IL_0013: stloc.2
IL_0014: ldloc.2
IL_0015: isinst System.Guid
IL_001a: brtrue.s IL_003a
IL_001c: ldloc.2
IL_001d: isinst Error
```

The custom union is different.
The compiler calls its `TryGetValue` methods and never reads `Value`:

```cil
// CustomUnion: HandleCustomUnion(Succeeds) switch { Guid => 201, Error ... }
IL_000c: ldloca.s 1
IL_000e: ldloca.s 2
IL_0010: call bool ValueResult<System.Guid>::TryGetValue(!0&)
IL_0015: brtrue.s IL_0036
IL_0017: ldloca.s 1
IL_0019: ldloca.s 3
IL_001b: call bool ValueResult<System.Guid>::TryGetValue(Error&)
```

Nothing gets boxed, on either side.
The cost moves to the struct size: `ValueResult<Guid>` holds a `Guid`, an `Error` reference, and a `bool`, so every copy moves 32 bytes instead of 8.

## The Benchmark

Each benchmark does what an endpoint does: get the outcome from a handler and map it to a status code.
The handler is a method the JIT can't inline, so the outcome is really created:

```csharp
[Params(true, false)]
public bool Succeeds { get; set; }

[Benchmark(Baseline = true)]
public int ResultClass()
{
    Result<Guid> result = HandleResult(Succeeds);

    if (result.IsSuccess)
    {
        return 201;
    }

    return result.Error.Code switch
    {
        "Bookings.Overlap" => 409,
        _ => 500
    };
}

[Benchmark]
public int UnionOfRecords() => HandleUnion(Succeeds) switch
{
    BookingReserved => 201,
    ApartmentNotFound => 404,
    Overlap => 409
};

[MethodImpl(MethodImplOptions.NoInlining)]
private static Result<Guid> HandleResult(bool succeeds) =>
    succeeds ? Id : Result.Failure<Guid>(BookingErrors.Overlap);

[MethodImpl(MethodImplOptions.NoInlining)]
private static ReserveBookingResult HandleUnion(bool succeeds) =>
    succeeds ? new BookingReserved(Id) : new Overlap(Start, End);
```

The generic and custom unions follow the same pattern.
A second set of benchmarks puts each handler behind an `async` method that completes synchronously, which is the shape of a command handler that returns a `Task`.

I ran it with [**BenchmarkDotNet**](https://benchmarkdotnet.org/) 0.15.8 on .NET SDK 11.0.100 (runtime 11.0.0), on an AMD Ryzen 9 9950X3D under Windows 11.
BenchmarkDotNet 0.15.8 doesn't recognize `net11.0` when it builds a separate benchmark process, so the run uses its in-process toolchain.

## Results Without Async

| Return type | Success: time | Success: allocated | Failure: time | Failure: allocated |
| --- | --- | --- | --- | --- |
| Result class | 8.1 ns | 48 B | 5.0 ns | 48 B |
| Union of records | 2.8 ns | 32 B | 3.2 ns | 24 B |
| Generic union | 2.8 ns | 32 B | 2.0 ns | 0 B |
| Custom union | 5.2 ns | 0 B | 2.1 ns | 0 B |

The **Result class** allocates 48 bytes on every call.
On failure, the `Error` is cached, but `Result.Failure<Guid>` still creates a new `Result`.

The **union of records** allocates only the record: 32 bytes for `BookingReserved` and 24 bytes for `Overlap`.

The **generic union** boxes the `Guid` on success, and the box is 32 bytes, the same as the record.
On failure it stores the cached `Error` reference and allocates nothing.

The **custom union** is the only one with 0 bytes on success, but it was the slowest union on that path.
It skips the box, but every return copies a 32-byte struct instead of an 8-byte one.

## Results Behind an Async Handler

| Return type | Success: time | Success: allocated | Failure: time | Failure: allocated |
| --- | --- | --- | --- | --- |
| Result class | 21.5 ns | 192 B | 17.9 ns | 192 B |
| Union of records | 15.8 ns | 176 B | 15.6 ns | 168 B |
| Generic union | 16.5 ns | 176 B | 14.9 ns | 144 B |
| Custom union | 20.4 ns | 168 B | 18.4 ns | 168 B |

Every row allocates 144 to 192 bytes.
Most of that is two `Task` objects: the one the handler returns and the benchmark method's own `Task<int>`.
The return type only changes the remainder.

The custom union loses its advantage here.
The handler's `Task` stores the result, so a 32-byte struct makes that `Task` bigger.
On success it saved 8 bytes over the boxing generic union and took 4 ns longer.
On failure it was 24 bytes worse than the generic union.

## Does It Matter?

Not for a typical command handler.
The largest gap without async was about 5 ns and 48 bytes per call.
A handler that loads an apartment from a database waits on a network round trip that takes far longer than that.

Choose between the Result pattern and unions for what the compiler checks.
A union lists every outcome in the return type, and a `switch` expression without a `_` arm warns when a new outcome is missing.
The [**newsletter issue**](https://milanjovanovic.tech/blog/csharp-union-types-vs-result-pattern) walks through that with a real endpoint.

Write a custom non-boxing union only when a profiler shows union boxing on a hot path.
Even then, measure it, because in this benchmark the bigger struct cost more than the box it saved.

## Summary

A compiler-generated union is a struct with one `object` field.
Records go in as they are, and value types such as `Guid` get boxed.
The `Result<T>` class allocates a new object on every call, including failures with a cached `Error`.

Without async, every union was faster than the Result class, by 2 to 5 ns.
Behind an `async` handler, the `Task` allocation was larger than any of the return types, and all four landed between 15 and 22 ns.

## Frequently asked questions

### Are C# 15 union types faster than the Result pattern?

In my BenchmarkDotNet run on .NET 11, creating and matching a union took 2 to 5 ns, against 5 to 8 ns for a Result class, and the union allocated 0 to 32 bytes against 48. Behind an async method the gap shrank to a few nanoseconds, because the Task allocation (144 to 192 bytes) was larger than any of the return types.

### Does a C# union box value types?

Yes. A union declaration compiles to a struct with one object field, so a value-type case such as a Guid is boxed when you create the union. A Guid box was 32 bytes in my benchmark, the same as a record with one Guid property. Reference-type cases, such as records, are stored as they are.

### How do I write a C# union that does not box?

Write the union by hand: a struct with the [Union] attribute that implements IUnion, keeps each case in a typed field, and has a TryGetValue method per case. A switch expression uses TryGetValue, so matching a Guid case allocated 0 bytes in my benchmark. It was slower than the boxing union on the success path, though, because the struct is larger to copy.

### Does the Result class allocate on failure?

Yes. Result.Failure creates a new Result object even when the Error is a cached static field. In my benchmark that was 48 bytes per call for success and failure alike.

### Should I switch from the Result pattern to unions for performance?

No. The differences were a few nanoseconds and a few dozen bytes per call, while a command handler usually waits on a database for far longer. Choose between them for design reasons, such as compiler checks on every outcome.
