Technology

C# 15 Union Types: Almost a Rust Enum

18 Nov 2026

C# 15, which shipped with .NET 11 last week, finally lets a value be "one of these types and nothing else", and makes the compiler check that you've handled every case. I write C# for a living and Rust for fun, so I've wanted this for a long time. It's good. It's also not quite what Rust has, and the differences are worth knowing before you start using it.

The problem it solves

How do you return "a result, or one of several kinds of failure" in C#? Until now, the options have all been a bit unsatisfying:

  • Exceptions. They don't show up in the method signature, so the caller has to know.
  • A base class or interface with subclasses. Anyone can add another subclass, so the compiler can never say a switch covers everything. You end up writing _ => throw new UnreachableException() and hoping.
  • A hand-written Result type, or a library like OneOf. It works, but it's not part of the language.

What these are all missing is the thing I like most about Rust's enum: add a new case, and the compiler shows you every place that doesn't handle it yet.

What it looks like

public sealed record Card(string Last4);
public sealed record Invoice(int DueInDays);
public sealed record Cash;

public union Payment(Card, Invoice, Cash);

A Payment is exactly one of those three. Each case type converts to it implicitly:

Payment payment = new Invoice(30);

And a switch over it needs no catch-all arm:

string Describe(Payment payment) => payment switch
{
    Card c => $"card ending {c.Last4}",
    Invoice i => $"invoice, due in {i.DueInDays} days",
    Cash => "cash",
};

If someone adds a fourth case to Payment, every switch that doesn't handle it gets a warning. That's the whole point.

Unions can be generic, so C# can finally have a proper Result:

public sealed record Ok<T>(T Value);
public sealed record Failed(string Reason);

public union Result<T>(Ok<T>, Failed);

The same thing in Rust

enum Payment {
    Card { last4: String },
    Invoice { due_in_days: u32 },
    Cash,
}

fn describe(payment: &Payment) -> String {
    match payment {
        Payment::Card { last4 } => format!("card ending {last4}"),
        Payment::Invoice { due_in_days } => format!("invoice, due in {due_in_days} days"),
        Payment::Cash => "cash".to_string(),
    }
}

On the surface they're almost the same. Underneath, there are three differences.

1. C# combines existing types, Rust declares the cases

In Rust the variants live inside the enum. In C#, each case is a type of its own, declared separately, and the union just lists them. That's more typing for small cases, but it has an upside: the same type can be a case in several unions. A Card can be part of Payment and of StoredCredential at the same time. You can also use types you don't own: union IntOrString(int, string) is perfectly legal.

2. A union can be empty

This is the big one. The compiler turns a union into a struct that holds the value in a single object? property. Structs always have a default value, and the default union holds null:

Payment payment = default;
Describe(payment); // throws SwitchExpressionException

The switch the compiler happily accepted as complete throws at runtime. In the common case you don't even get a warning. Default values sneak in through fields you forgot to initialize and freshly created arrays. Microsoft's own documentation is blunt about it: handle null whenever a default value can reach your switch.

So add a null arm, not a _ arm:

    Cash => "cash",
    null => "no payment",

A discard arm also swallows any case you add later, so you'd lose exactly the warning you wanted. In Rust there is no such state: an enum value is always one of its variants. If you want "maybe nothing", you say so with Option.

3. Value types get boxed

Because the value is stored as object?, a union IntOrString(int, string) allocates on the heap whenever it holds an int. A Rust enum is a tag plus room for its largest variant, stored inline, with no allocation. C# lets you write your own union type that avoids boxing, but that's a page of hand-written code. For the common case, a union of records (which live on the heap anyway), it doesn't matter.

Closed hierarchies: the other half

C# 15 also adds the closed modifier, and it gets you even closer to Rust:

public closed record class Payment;
public sealed record Card(string Last4) : Payment;
public sealed record Invoice(int DueInDays) : Payment;
public sealed record Cash : Payment;

A closed class can only be derived from inside its own assembly, so the compiler knows every subclass, and the same switch is checked for completeness. The cases are declared together and belong to Payment, just like Rust's variants. And since it's an ordinary class, there's no hidden default value: null is handled by nullable reference types, like everywhere else in modern C#.

Microsoft's rule of thumb is a good one: use a union to combine types that already exist, and a closed hierarchy when you own the types. For most of the domain models I write at work, I suspect closed hierarchies will be the better tool. One catch: closed only covers direct subclasses, so if you have a deeper hierarchy, mark the classes in the middle closed too.

When I'll actually use them

Unions need types that ship with the .NET 11 runtime, and .NET 11 is a Standard Term Support release. At work we're on .NET 10, the long-term support version, and I suspect most companies are. So realistically, union types arrive in my day job with .NET 12, the next LTS, in November 2027. In hobby code, I can use them today.

Verdict

A good feature, and a late one. The compiler finally tells you when you've forgotten a case, which is the thing I miss most every time I switch from Rust back to C#. The empty default value is the price of adding this to a language where every struct has one, and it's worth knowing about before it bites you in production.

C# gets a little more like Rust every year. I'm not complaining.

More on this month's releases in Rust 1.100, .NET 11 and a Busy November.

Sources: What's new in C# 15, Union types (C# reference), Announcing .NET 11.

Comments

No comments yet.

Log in to leave a comment.