C# Union Types vs the Result Pattern: Performance

csharpdotnetperformance
C# Union Types vs the Result Pattern: 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?. 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 article, trimmed here to its shape:

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:

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>:

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:

[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:

.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:

// 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:

// 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:

// 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:

[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 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 typeSuccess: timeSuccess: allocatedFailure: timeFailure: allocated
Result class8.1 ns48 B5.0 ns48 B
Union of records2.8 ns32 B3.2 ns24 B
Generic union2.8 ns32 B2.0 ns0 B
Custom union5.2 ns0 B2.1 ns0 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 typeSuccess: timeSuccess: allocatedFailure: timeFailure: allocated
Result class21.5 ns192 B17.9 ns192 B
Union of records15.8 ns176 B15.6 ns168 B
Generic union16.5 ns176 B14.9 ns144 B
Custom union20.4 ns168 B18.4 ns168 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 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.

  • C# Records: When and How to Use Them

    Records in C# provide value equality, immutability, and concise syntax. Use them for DTOs, commands, queries, and events, and keep classes for entities and mutable state.

Loading comments...

Whenever you're ready, there are 5 ways I can help you:

  1. Pragmatic Self-Hosting: Learn to deploy and run your apps on a VPS with Dokploy and Tailscale. Keep administration private, automate releases, and practice restoring backups, with source code and a runbook you can reuse.
  2. Pragmatic Clean Architecture: Join 5,000+ students in this comprehensive course that will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture.
  3. Modular Monolith Architecture: Join 2,800+ engineers in this in-depth course that will transform the way you build modern systems. You will learn the best practices for applying the Modular Monolith architecture in a real-world scenario.
  4. Pragmatic REST APIs: Join 1,900+ students in this course that will teach you how to build production-ready REST APIs using the latest ASP.NET Core features and best practices. It includes a fully functional UI application that we'll integrate with the REST API.
  5. Patreon Community: Join a community of 5,000+ engineers and software architects. You will also unlock access to the source code I use in my YouTube videos, early access to future videos, and exclusive discounts for my courses.

The .NET Weekly

One practical .NET tip, every Saturday.

Join 66,000+ engineers who read it. Free, and you can unsubscribe any time.