RO EN

Union types in C# 15: a practical guide, from Result<T> to APIs

Union types in C# 15: a practical guide, from Result<T> to APIs ✨ Imagine generată cu AI
Doru Bulubașa
25 November 2026
56 views

Every C# developer has written, in one form or another, the same function: try something and return either the result, or the reason why it failed. Until now, we only had approximations: exceptions, a bool with an out parameter, a class hierarchy, or a library like OneOf. They all work, but none tells the compiler the most important thing: these are all the possible variants.

C# 15, released along with .NET 11, solves exactly this with union types. This article is a practical guide: the syntax, what the compiler actually generates, the pattern matching rules (including some pitfalls), a Result<T> used end-to-end, behavior in APIs and JSON, and when it’s worth choosing something else.

How we modeled "either one or the other" until now

Approach Problem
Exceptions They don’t appear in the method signature, cost at throwing, and turn normal business cases ("invoice does not exist") into error flows.
bool TryX(out T) Works for two cases, but doesn’t say why it failed and doesn’t compose with async.
Class hierarchy Anyone can add a subclass, so the compiler cannot guarantee that a switch handled everything. You end up with a _ => throw branch "just in case".
OneOf and other libraries Good and mature, but use Match with lambdas or T0/T1 properties, not native pattern matching.

Common missing point: none provide compiler-checked exhaustiveness. When someone adds a new case, you find out in production.

Basic syntax

A union declares a type whose value is one of several case types. The component types are existing types that don’t need to have anything in common. We continue the example from the .NET 11 article, the status of an invoice sent in e-Invoice:

public sealed record Accepted(string UploadIndex);
public sealed record Rejected(string[] Errors);
public sealed record Pending(DateTimeOffset Since);

public union SubmissionResult(Accepted, Rejected, Pending);

Each component type has an implicit conversion to the union, so you don’t need factories or wrappers:

SubmissionResult result = new Accepted("5012345678");

string message = result switch
{
    Accepted a => $"Accepted, index {a.UploadIndex}",
    Rejected r => $"Rejected: {string.Join("; ", r.Errors)}",
    Pending p  => $"Processing since {p.Since:HH:mm}",
};

If you try to assign a type not in the list, you get a compile error. And if tomorrow you add Cancelled in the declaration, the compiler signals every switch that doesn’t handle the new case. That’s actually the whole idea.

Component types can be practically anything: classes, structs, interfaces, nullable types, generic parameters, even other unions. A union IntOrString(int, string) is perfectly valid.

What the compiler generates

It’s worth knowing what’s under the hood, because it explains almost all the rules below. According to the language reference, a union declaration becomes:

  • a struct marked with the [Union] attribute, implementing the IUnion interface (both in System.Runtime.CompilerServices, included in the .NET 11 runtime);
  • a public constructor for each component type;
  • a Value property of type object?, holding the content.

From this follow three practical consequences:

  • Value types are boxed. A union IntOrString(int, string) receiving 42 allocates on the heap. In usual code it doesn’t matter, but in a hot loop it shows. We’ll see below how to avoid this.
  • The default value has null content. Being a struct, default(SubmissionResult) exists and contains none of the cases. We’ll return to this in exhaustiveness.
  • You don’t get equality, cloning, or deconstruction as you do from a record. The union is a container, not a value type with its own semantics.

Pattern matching: what is actually tested

The basic rule: type patterns apply to the content, not the union. When you write result is Accepted a, the compiler tests result.Value. Most rules naturally follow from this, but some surprise:

Pattern Applies to Example
Type or declaration Content (Value) result is Rejected r
Typed properties Content result is Rejected { Errors.Length: > 3 }
Untyped properties The union members themselves result is { Value: not null }
var and _ The union itself result is var r
null Content result is null is true for default
  • result is SubmissionResult does not compile (CS8121): a type pattern must correspond to at least one component type.
  • { } matches even an empty union, because it tests the struct, not the content. To check that a value exists, write result is not null.

Exhaustiveness and the default value trap

A switch is exhaustive when it handles all component types. The problem appears with the case you don’t see: the empty union.

SubmissionResult result = default; // Value == null

string message = result switch
{
    Accepted a => "...",
    Rejected r => "...",
    Pending p  => "...",
};
// SwitchExpressionException at runtime

If all component types are non-nullable, the compiler considers the content "not null" and doesn’t warn you. A default slipped from an uninitialized array or an unassigned class field still reaches runtime and throws an exception. Two recommendations from the documentation are worth remembering:

  • Prefer a null branch instead of a _ one. The _ (or var) branch catches also cases added in the future, so the compiler no longer warns you when Cancelled appears. The null branch handles the empty union and preserves exhaustiveness checking.
  • If a component type is nullable (for example union MaybePet(Cat?, Dog)), the compiler explicitly requires a null branch (warning CS8655).
string message = result switch
{
    Accepted a => $"Accepted, index {a.UploadIndex}",
    Rejected r => $"Rejected: {string.Join("; ", r.Errors)}",
    Pending p  => $"Processing since {p.Since:HH:mm}",
    null       => throw new InvalidOperationException("Uninitialized result"),
};

Unions with members and generic unions

A union can have a body, with methods and computed properties, just like a struct. Restrictions: no instance fields, no auto-properties, and public constructors with a single parameter are reserved for those generated by the compiler.

public union SubmissionResult(Accepted, Rejected, Pending)
{
    public bool IsFinal => this is Accepted or Rejected;
}

Unions can also be generic, which opens the way to the most useful type in the whole story.

An end-to-end Result<T>

Here is a minimal result type, used in a service and in a Minimal API endpoint:

public sealed record Error(string Code, string Message);

public union Result<T>(T, Error);
public sealed class InvoiceService(AppDbContext db)
{
    public async Task<Result<Invoice>> GetAsync(int id, CancellationToken ct)
    {
        var invoice = await db.Invoices.FindAsync([id], ct);
        if (invoice is null)
            return new Error("invoice.not_found", $"Invoice {id} does not exist.");

        if (invoice.IsCancelled)
            return new Error("invoice.cancelled", $"Invoice {id} was cancelled.");

        return invoice; // implicit conversion to Result<Invoice>
    }
}
app.MapGet("/invoices/{id:int}", async (int id, InvoiceService service, CancellationToken ct) =>
    await service.GetAsync(id, ct) switch
    {
        Invoice invoice                       => Results.Ok(invoice),
        Error { Code: "invoice.not_found" } e => Results.NotFound(e),
        Error e                               => Results.UnprocessableEntity(e),
        null                                  => Results.Problem(),
    });

Business errors are now values, visible in the method signature, and the endpoint cannot "forget" a case. Exceptions remain for what they are truly exceptional: database down, a bug.

A pitfall to know: if you instantiate Result<Error>, both component types become Error, and the implicit conversion becomes ambiguous, so the compiler errors. For the same reason, avoid unions where one component type can contain another (for example object alongside string).

Union, closed hierarchy, OneOf or exceptions?

C# 15 also brings closed hierarchies: the closed modifier on a base class forbids derivation outside the assembly, so the compiler knows all descendants. The two mechanisms partially overlap, so the choice rule matters:

Situation Choice
Combining existing types, without a common base (Invoice and Error) union
Modeling a family of types you control, with common data and behavior closed hierarchy
Public API contract, where the client must know exactly which case it received closed hierarchy with JSON discriminator (see next section)
Code on .NET 10 or older, or multi-target library OneOf, still
Truly unexpected error (infrastructure, bug) exception

Unions in APIs and JSON

ASP.NET Core 11 supports unions anywhere System.Text.Json is used: request and response bodies in Minimal APIs and MVC, SignalR with JSON protocol, JavaScript interop in Blazor. In the OpenAPI document, a union appears as anyOf with the schema of each component type. However, there are three details to keep in mind when putting it in a public contract.

1. There is no discriminator

Unlike polymorphic types, the union serializes as the inner value, without a $type field. For Result<Invoice>, the client receives either the invoice JSON or the error JSON and must figure out which is which.

2. Deserialization guesses by JSON shape

On reading, System.Text.Json chooses the case by the JSON token type. union IntOrString(int, string) works fine, because a number and a string differ. But union Pet(Cat, Dog), where both are objects, fails with an ambiguity error. The solution is a custom classifier, attached via the [JsonUnion] attribute, which inspects properties and decides the case. Andrew Lock documented in detail how inconvenient this is in practice, in the .NET 11 previews.

[JsonUnion(TypeClassifier = typeof(PetClassifier))]
public union Pet(Cat, Dog);

3. Only in the request body

Unions don’t bind from route, query string, headers, or form fields. In SignalR they work only with the JSON protocol, not with MessagePack or Newtonsoft.Json.

My pragmatic recommendation: use unions freely inside the application, between services, handlers, and domain, and at the API boundary map them explicitly to DTOs or HTTP responses, as we did in the endpoint above. The public contract remains stable and easy to consume from any language.

Custom unions without boxing

If the union is on a hot path and contains value types, the boxing in the generated implementation can matter. The language reference allows writing manually a type recognized as a union: any class or struct marked with [Union], with one public constructor with a parameter for each case and a Value property. If you also add HasValue and TryGetValue(out T) methods, the compiler uses them in pattern matching instead of the Value property, so no boxing.

[Union]
public readonly struct AmountOrCode : IUnion
{
    private readonly decimal _amount;
    private readonly string? _code;
    private readonly byte _kind; // 0 = empty, 1 = amount, 2 = code

    public AmountOrCode(decimal amount) { _amount = amount; _kind = 1; }
    public AmountOrCode(string code)    { _code = code;     _kind = 2; }

    public object? Value => _kind switch { 1 => _amount, 2 => _code, _ => null };
    public bool HasValue => _kind != 0;

    public bool TryGetValue(out decimal amount) { amount = _amount; return _kind == 1; }
    public bool TryGetValue(out string? code)   { code = _code;     return _kind == 2; }
}

It’s more code, so it’s worth it only when the profiler shows allocations matter. For 95% of cases, the one-line declaration is the right choice.

Migrating from OneOf

  • Don’t rewrite everything at once. Unions require .NET 11 and C# 15. Libraries that must run on .NET 10 remain on OneOf.
  • Start with new types and service boundaries: methods returning OneOf<Invoice, NotFound, Error> are natural candidates.
  • Replace Match with switch and remove _ branches that existed only to silence the compiler. Put a null branch instead.
  • Check serialization before any type crossing the API boundary. OneOf and native unions do not produce the same JSON.

Common mistakes

  • The _ branch out of reflex. It cancels exactly the benefit for which you use the union: the warning on new cases.
  • Ignoring the default value. An empty union in an array or uninitialized field throws SwitchExpressionException with no compile warning.
  • Public unions in APIs without a serialization plan. Without a discriminator, the client guesses, and cases with the same JSON shape don’t deserialize at all without a classifier.
  • Overlapping component types. Result<Error> or object alongside other types lead to ambiguous conversions.
  • Unions everywhere. If two variants share much behavior, a closed hierarchy with virtual methods is often cleaner than a switch repeated in ten places.

Conclusion

Union types are the most important modeling change in C# since the introduction of pattern matching. They don’t bring anything that couldn’t be done before with enough discipline, but they move the discipline into the compiler: possible cases are declared in one place, and any switch that forgets one is signaled at build time, not in production.

A few rules to remember: use unions for results and states inside the application, prefer the null branch instead of _, map explicitly at the API boundary, and write custom unions only when the profiler demands it.

If you haven’t yet read what else .NET 11 brings besides C# 15 and how to decide on upgrading, you can find everything in the article about the .NET 11 release.

Sources and documentation