Union types are my favorite feature in C# 15.
The discriminated unions proposal was opened on the C# language repository in February 2017.
9 years later, unions finally ship with .NET 11.
It's the biggest change to the C# type system since records arrived in C# 9, 6 years ago.
And honestly, it's the worst time for releasing this feature.
Now, as AI agents write 99% of our code, could developers still enjoy the feature they wanted for ages?
We, developers, enjoyed our craft for years.
It was such a pleasure when you worked the whole day, and finally, at the end, your feature was ready.
Developers like me, who have 10 or more years of experience, have a big advantage over new developers who started 1-3 years ago, and all because of AI.
We wrote all the code by hand, and really enjoyed it.
We faced problems and pitfalls. We had late-night debugging sessions.
We were reading logs line by line at 2 am.
All the experience we got was real, based on real tasks, real problems that we figured out and fixed ourselves.
Now all of that can do AI for us.
In all of my projects, I have a backbone code architecture, and all the templates were created by me, by hand.
I'm 100% sure that my own written code is better than what AI writes.
Because AI was trained on hundreds of thousands of open-source repositories, most of which contain really bad code.
That's why I always hand out my own code examples to AI and it writes code like me.
I really want to enjoy the release of discriminated unions.
That's why I'm returning to the origins.
I will sit down for a few days and I will write code by hand to finally enjoy this feature.
And you can do this too.
Later, I will create AI skills (based on my code) so Claude will use Union types in all of my new projects on .NET 11.
If you are new to union types, a union is a type that can have one value from a fixed set of types.
The compiler knows that set and checks that your code handles every case.
In this post, we will explore:
- Why C# Needed Union Types
- Declaring Your First Union
- Pattern Matching and Exhaustiveness
- Adding Members to a Union
- Closed Hierarchies
- Closed Enums: Coming Next
- Unions in System.Text.Json
- Unions in ASP .NET Core
- Making Your Result Type Union-Aware
- Custom Unions and Performance
- Unions and EF Core
- Best Practices for Union Types
Let's dive in!
👉 Read original article on my newsletter: https://antondevtips.com/blog/union-types-in-csharp-15-the-most-awaited-feature-in-6-years
Why C# Needed Union Types
Say you're building a checkout service that accepts three payment methods.
Each method carries different data.
Before C# 15, the usual approach was a marker interface:
public interface IPaymentMethod; public sealed record CardPayment(string Number) : IPaymentMethod; public sealed record PayPalPayment(string Email) : IPaymentMethod; public sealed record BankPayment(string Iban) : IPaymentMethod; public static string Describe(IPaymentMethod payment) => payment switch { CardPayment card => $"Card ending in {card.Number[^4..]}", PayPalPayment paypal => $"PayPal account {paypal.Email}", BankPayment bank => $"Bank transfer to {bank.Iban}", _ => throw new ArgumentOutOfRangeException(nameof(payment), "Unknown payment method") }; Look at the last line.
You handle all 3 payment methods, but you still need a _ branch that throws.
The compiler can't know that only three types implement IPaymentMethod.
Any class in any assembly can implement it (that you don't control).
So when a teammate adds ApplePayPayment next month, the code still compiles.
You find out about the missing case in production when the exception fires.
The other option was object, which is even worse: it accepts literally anything.
Libraries like OneOf, ErrorOr and FluentResults filled this gap for years.
They're generic wrappers that the compiler doesn't understand, so they can't give you real language-level exhaustiveness checks.
C# 15 fixes this in the language itself.
Declaring Your First Union
You declare a union with the union keyword, a name, and a list of case types:
public record class CreditCard(string Number, string Holder, DateOnly Expiry); public record class PayPal(string Email); public record class BankTransfer(string Iban, string Bic); public union PaymentMethod(CreditCard, PayPal, BankTransfer); The case types don't need a common base class or interface.
They can be completely unrelated types.
The compiler adds an implicit conversion from each case type, so you assign them directly:
PaymentMethod payment = new PayPal("john@example.com"); Console.WriteLine(payment.Value); // output: PayPal { Email = john@example.com } payment = new CreditCard("4111111111111111", "John Doe", new DateOnly(2028, 12, 1)); Console.WriteLine(payment.Value.GetType().Name); // output: CreditCard The Value property holds the current case.
Anything that isn't a case type is rejected at compile time:
PaymentMethod payment = "oops"; // error CS0029: Cannot implicitly convert type 'string' to 'PaymentMethod' Case types can be any type that converts to object: classes, structs, interfaces, type parameters, nullable types and even other unions.
Here's a union of 2 built-in types.
An order can be referenced either by its database ID or by an external order number:
public union OrderReference(int, string); OrderReference byId = 42; OrderReference byNumber = "EXT-1042"; Unions can be generic too.
Here's a classic Option<T> type:
public record class None; public record class Some<T>(T Value); public union Option<T>(None, Some<T>); What the Compiler Generates
A union declaration is shorthand.
The compiler turns PaymentMethod into a struct like this:
[Union] public struct PaymentMethod : IUnion { public PaymentMethod(CreditCard value) => Value = value; public PaymentMethod(PayPal value) => Value = value; public PaymentMethod(BankTransfer value) => Value = value; public object? Value { get; } } You get one constructor per case type and a single Value property of type object?.
The [Union] attribute and the IUnion interface live in System.Runtime.CompilerServices.
Note: C# unions are unions of types. They aren't "tagged" by name like F# or Rust enums. To get a discriminated union, declare a small record for each case, as
PaymentMethoddoes.
👉 Read original article on my newsletter: https://antondevtips.com/blog/union-types-in-csharp-15-the-most-awaited-feature-in-6-years

