Abstract visualization with Type Unions text, geometric shapes and code elements
Back to blog
dotnetc#.NET 11

Union Types in C# 15: What Became of the 2024 Proposal

Sascha KieferDevelopment

TL;DR

  • C# 15 declares unions over existing types: `union Shape(Circle, Rectangle);`. The compiler warns when a `switch` misses a case.
  • For your own hierarchies there are `closed` classes: all direct subtypes live in the same assembly, so a `switch` no longer needs a default arm.
  • Both are on by default for `net11.0`, no `LangVersion preview` needed.

In 2024 my post on discriminated unions still had a “maybe” in the title. With C# 15 they have arrived, though differently from the proposal back then: `union` combines existing types, `closed` seals class hierarchies. What that gets you, where it falls short and where to start.

In September 2024 I wrote about discriminated unions in C# here, with a “maybe” in the title. There was only a proposal, and nobody could say whether or when it would become a feature. So the post ended with: “It remains to be seen whether and when this long-awaited feature will find its way into C#.”

With C# 15 and .NET 11 that question is answered: union is now a keyword. The feature does look different from my post, though. The proposal described five variants; what shipped are two building blocks. union combines existing types, closed seals a class hierarchy. I like this solution better than what I presented back then.

The shape example in C# 15

In 2024 I could only show the draft from the proposal. This is the same example today, and it compiles:

public record Circle(double Radius);
public record Rectangle(double Width, double Height);

public union Shape(Circle, Rectangle);

That's all it takes. Circle and Rectangle are plain records with no shared base class or interface. Only the union defines that a Shape is exactly one of the two.

Assignment is implicit. A type that is not on the list causes a compile error:

Shape shape = new Circle(10);
Shape other = "circle"; // error: string is not a case of Shape

In a switch, the compiler checks that every case is handled:

var area = shape switch
{
    Circle c => Math.PI * c.Radius * c.Radius,
    Rectangle r => r.Width * r.Height,
};

The real benefit shows when Shape later gets a Triangle. Until now the triangle would have ended up unnoticed in the default arm or thrown an exception at runtime. Now the compiler warns at every place that doesn't handle the new case.

The types in a union don't need to be related. Classes, structs, interfaces and other unions are allowed, which includes types from third-party libraries you can't change.

Where it falls short

Three things you should know before you get started.

A missing case is only a warning, not an error. I would have preferred an error. If your build already treats warnings as errors, nothing changes. If it doesn't, this is a good reason to turn it on. Also, don't add a _ arm as a safeguard: it covers every case added later as well, and then there is no warning anymore.

A union can be empty. default(Shape) holds neither a circle nor a rectangle but null. A switch without a null arm then throws a SwitchExpressionException, exactly the runtime error the union was supposed to prevent. Empty unions come from default, from newly allocated arrays, or when System.Text.Json reads a null from the JSON.

Internally a union is a struct holding an object?. Value types are boxed. The compiler generates no == operator; Equals works, but uses the runtime's general-purpose struct comparison. For domain objects this hardly matters. If you process millions of small structs in a loop, measure it.

closed for your own class hierarchies

A lot is written about union, little about closed. Yet it makes a line redundant that shows up all the time in many codebases:

_ => throw new InvalidOperationException($"Unknown state: {state}")

It's needed because with an abstract base class the compiler can't know whether there are more subclasses. With closed it knows:

public closed record class OrderState;
public record class Placed : OrderState;
public record class Paid(DateTimeOffset At) : OrderState;
public record class Shipped(string TrackingNumber) : OrderState;
public record class Cancelled(string Reason) : OrderState;

public static string Describe(OrderState state) => state switch
{
    Placed => "received",
    Paid(var at) => $"paid on {at:d}",
    Shipped(var tracking) => $"on its way, tracking number {tracking}",
    Cancelled(var reason) => $"cancelled: {reason}",
};

This switch needs no default arm. A closed class is implicitly abstract, and all direct subclasses must be in the same assembly. That only applies to the first level: a subclass is open again unless you mark it closed as well. Interfaces and enums can't be closed in C# 15.

When to use which? If you own the types and they share data or behavior, closed fits. If you want to combine types that have nothing to do with each other, say a result from your domain and an error type from a library, union fits.

What about OneOf?

You don't have to rewrite existing code right away. Your own classes and structs get the same compiler check with [Union], matching constructors and a Value property. An existing Result<T> class can stay and still benefit.

.NET 11 doesn't ship ready-made types like Option<T> or Result<T, TError>; the documentation only shows them as hand-written examples. I hope that changes with C# 16.

A good starting point is searching your repository for _ => throw and default => throw. Every hit is a case that until now would only have surfaced at runtime. With closed or union, the compiler reports it as soon as someone adds a new state.

Sources

Need support?

Unions and closed classes pay off most in domain logic, where a forgotten case otherwise only shows up in production. As a .NET development partner we move existing C# codebases to .NET 11 and show where the new language features prevent real bugs and where they would just be busywork. If you want that assessed for your application, get in touch.

.NET development at vensas