Post

Union types are in C# 15. What do you actually get?

Meetup registration examples show how unions work, how switch expressions catch a missing case, and when a union allocates memory.

Union types are in C# 15. What do you actually get?

.NET 11 was released on November 10, and with it came C# 15. The feature I was waiting for most was union types. People have asked for them for years, usually under the name “discriminated unions”.

The old way

When someone registers for a meetup, they either get a seat or land on the waiting list. The two results have nothing in common, so there is no natural base class for them. Until now, you could force a shared base class, add a marker interface, use a library like OneOf, or just use object:

1
2
3
4
5
6
7
8
object result = new OnWaitingList(Position: 7);

var message = result switch
{
    Registered r => $"See you there! Your seat is {r.SeatNumber}.",
    OnWaitingList w => $"You are number {w.Position} on the waiting list.",
    _ => throw new InvalidOperationException("Unknown registration result")
};

The last arm is the problem. The compiler has no idea that only two types are allowed, so you need the discard. If someone adds a third result next year, the compiler won’t point you to this switch and you will find out at runtime.

The union keyword

In C# 15, you declare the set of allowed types yourself:

1
2
3
4
public record Registered(int SeatNumber);
public record OnWaitingList(int Position);

public union Registration(Registered, OnWaitingList);

Registered and OnWaitingList are called case types. They are normal types, and they don’t need to know anything about Registration.

Every case type converts to the union implicitly, so assignments look natural. Any other type gives you a compile error:

1
2
3
Registration registration = new Registered(SeatNumber: 42);
registration = new OnWaitingList(Position: 7);
registration = "Seat 42"; // error CS0029

Exhaustive switch without the discard

Pattern matching works on the value inside the union, so you write the same type patterns as before:

1
2
3
4
5
var message = registration switch
{
    Registered r => $"See you there! Your seat is {r.SeatNumber}.",
    OnWaitingList w => $"You are number {w.Position} on the waiting list.",
};

There is no discard arm and no warning because the compiler knows the full list of case types. When you add a third case, for example RegistrationClosed, every switch expression that doesn’t handle it gets warning CS8509. A classic switch statement doesn’t have to cover every case, so it stays silent.

I would treat that warning as an error. Exhaustiveness is the main reason to use unions, so a missing case should break the build:

1
2
3
<PropertyGroup>
  <WarningsAsErrors>$(WarningsAsErrors);CS8509</WarningsAsErrors>
</PropertyGroup>

Using it in an API endpoint

In a real app, the registration endpoint has one more outcome: someone can try to register for a meetup that doesn’t exist. That gives three cases, and each of them maps to a different HTTP response:

1
2
3
public record MeetupNotFound(int Number);

public union RegistrationResult(Registered, OnWaitingList, MeetupNotFound);
1
2
3
4
5
6
7
8
9
10
11
12
app.MapPost("/meetups/{number}/registrations",
    async (int number, RegistrationRequest request, RegistrationService service) =>
{
    RegistrationResult result = await service.RegisterAsync(number, request);

    return result switch
    {
        Registered r => Results.Created($"/meetups/{number}/registrations/{r.SeatNumber}", r),
        OnWaitingList w => Results.Accepted(value: w),
        MeetupNotFound => Results.NotFound(),
    };
});

Without unions, code like this often uses exceptions, nulls or a hand-written Result<T> class. With a union, all possible outcomes are listed in one declaration. When a new outcome appears, the compiler points to every switch expression that doesn’t handle it yet.

Members, but no extra state

A union can have a body with methods and computed properties. It can’t have state of its own, so instance fields, auto-properties and field-like events are not allowed:

1
2
3
4
5
6
7
8
9
public union Registration(Registered, OnWaitingList)
{
    public string Summary => this switch
    {
        Registered r => $"Seat {r.SeatNumber}",
        OnWaitingList w => $"Waiting list, position {w.Position}",
        null => "No registration",
    };
}

Watch out for default

The null arm in the previous example is there for a reason. A generated union is a struct, so default(Registration) exists, and its Value property is null. You can get such a value from an uninitialized field or an array element.

If all case types are non-nullable, the compiler doesn’t always warn you about a missing null arm. Without it, the switch throws SwitchExpressionException at runtime when it gets a default union. The docs recommend a null arm over a discard. A discard would also hide a missing case when you add a new type to the union, and then you lose the main benefit.

When one of the case types is nullable, for example public union NullableRegistration(Registered?, OnWaitingList);, the compiler warns about a missing null arm (CS8655).

To keep the examples short, the earlier switches have no null arm. They would throw on a default value, so in real code I would add one.

What does the compiler generate?

The compiler turns the union declaration into a struct with:

  • the [Union] attribute
  • the IUnion interface
  • one public constructor per case type
  • a Value property of type object?

The implicit conversions call those constructors, and pattern matching checks Value. It is syntactic sugar over a struct you could write yourself.

Remember that the value is stored as object?. Reference types go in as they are, but value types get boxed. Take a meetup reference that can be a number, like 171, or a URL slug. Every time you put a number in it, the union allocates:

1
public union MeetupRef(int, string);

In most business code you won’t notice it. In a hot loop, it can show up in your allocation profile.

Writing your own union type

The compiler doesn’t care whether you used the union keyword. Any class or struct is a union type when it has:

  • the [System.Runtime.CompilerServices.Union] attribute
  • one or more public constructors with a single parameter, one per case type
  • a public Value property of type object? or object

The main reason to write one by hand is performance: you can store the value in typed fields and avoid boxing. If you also add a HasValue property and a TryGetValue method per case type, the compiler calls TryGetValue for type patterns and HasValue for null patterns. It doesn’t need Value for those checks.

Here is my hand-written version of the meetup reference. The number lives in an int field, so matching on it doesn’t box:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System.Runtime.CompilerServices;

[Union]
public struct MeetupKey : IUnion
{
    private readonly int _number;
    private readonly bool _isNumber;
    private readonly string? _slug;

    public MeetupKey(int number)
    {
        _number = number;
        _isNumber = true;
    }

    public MeetupKey(string slug) => _slug = slug;

    public object? Value => _isNumber ? _number : _slug;

    public bool HasValue => _isNumber || _slug is not null;

    public bool TryGetValue(out int number)
    {
        number = _number;
        return _isNumber;
    }

    public bool TryGetValue(out string slug)
    {
        slug = _slug ?? "";
        return _slug is not null;
    }
}

A switch with int number and string slug arms on this type calls TryGetValue and doesn’t allocate for numbers. It is more code to maintain, so I would write it only when a profiler shows that boxing really costs you something.

How much does the boxing cost?

I didn’t want to guess, so I wrote a small benchmark with BenchmarkDotNet. Both methods create 1,000 meetup references from numbers and match them with the same switch expression:

1
2
3
4
5
6
7
8
9
10
for (int n = 0; n < 1_000; n++)
{
    MeetupRef meetup = n; // MeetupKey in the second benchmark
    sum += meetup switch
    {
        int number => number,
        string slug => slug.Length,
        null => 0,
    };
}
UnionMeanAllocated
union MeetupRef(int, string)2,330.7 ns24,000 B
hand-written MeetupKey233.8 ns0 B

The generated union boxes every number, so each value costs 24 bytes on the heap. The hand-written version doesn’t allocate at all and is about ten times faster in this loop. Still, 2.3 microseconds for 1,000 values is fast. I would only care about it on a hot path, like a parser or a message loop that runs millions of times.

Measured with BenchmarkDotNet 0.16.0-preview.2 on .NET 11.0.0, Apple M4, macOS.

Can I turn an existing Result type into a union?

Yes. A lot of teams already have their own Result or OneOf-style types, and you can turn them into unions without touching the callers. If the type has public single-parameter constructors and an object? Value property, the [Union] attribute is enough. If it uses a private constructor with factory methods, or a typed T Value property, you also need a small nested IUnionMembers interface that tells the compiler how to create the union and read its value.

What it is not

If you come from TypeScript, you might expect to write Registered | OnWaitingList anywhere in a method signature. C# 15 doesn’t support that. Every union is a named type that you declare first.

One reason is the runtime. TypeScript types disappear after compilation, but .NET types still exist when the program runs, so a union needs to be a real type.

It is also different from discriminated unions in F#: a C# union doesn’t define new data, it groups types you declare somewhere else. I see it as a compromise, and a sensible one for C#.

Does it still matter with AI agents?

Many of us now let agents write a big part of the code, so it is fair to ask if a new language feature changes anything. I think unions help here: an exhaustive switch gives the agent the same safety net it gives you. If a model adds a new case type and forgets one handler, the build fails, and the agent sees the error in its next step.

There is one catch: most models were trained on code written before C# 15, so they are likely to keep writing object switches and their own Result classes. The fix is cheap: tell them about the feature. If your project targets net11.0, a few lines in AGENTS.md or a similar instructions file are enough:

1
2
3
4
5
## C# 15
- This project targets net11.0, so C# 15 features are available.
- Use `union` types for a closed set of results instead of `object`,
  marker interfaces or hand-written Result classes.
- Handle every case in switch expressions over a union. Don't add a discard arm.

Try it

You need the .NET 11 SDK and a project that targets net11.0. C# 15 is the default language version there, so unions don’t need <LangVersion>preview</LangVersion> anymore.

If you want to go deeper, these were the most useful sources for me:

Cover image generated with gpt-image-2.5-sunburst from my photo.

This post is licensed under CC BY 4.0 by the author.