newsletter

Union Types in C# 15: The Most Awaited Feature in 6 Years

Download source code
10 min read

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!

Copied

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:

csharp
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.

Copied

Declaring Your First Union

You declare a union with the union keyword, a name, and a list of case types:

csharp
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:

csharp
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:

csharp
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:

csharp
public union OrderReference(int, string); OrderReference byId = 42; OrderReference byNumber = "EXT-1042";

Unions can be generic too. Here's a classic Option<T> type:

csharp
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:

csharp
[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 PaymentMethod does.

Copied

Pattern Matching and Exhaustiveness

When you pattern match on a union, the patterns apply to its Value. And the compiler knows the full list of cases:

csharp
public static string Describe(PaymentMethod payment) => payment switch { CreditCard card => $"Card ending in {card.Number[^4..]}", PayPal paypal => $"PayPal account {paypal.Email}", BankTransfer transfer => $"Bank transfer to {transfer.Iban}" };

There is no _ branch. You don't need one.

Forget a case, and the compiler tells you right away:

csharp
var name = payment switch { CreditCard => "card", PayPal => "paypal" }; // warning CS8509: The switch expression does not handle all possible values of its input type // (it is not exhaustive). For example, the pattern 'BankTransfer' is not covered.

Add a fourth case to PaymentMethod, and every switch in your codebase that doesn't handle it lights up with this warning. Turn on treat warnings as errors, and the build fails until you fix them all.

Property and List Patterns

All the patterns you already know work on the case types. For example, here's a fee calculator that charges more for cards that start with 3:

csharp
public static decimal GetFee(PaymentMethod payment, decimal amount) => payment switch { CreditCard { Number: ['3', ..] } => amount * 0.035m, CreditCard => amount * 0.029m, PayPal => Math.Round(amount * 0.034m + 0.30m, 2), BankTransfer => 0m };

Pay attention to where a pattern is applied. A type pattern unwraps the union, but a pattern without a type is applied to the union itself:

csharp
payment is PayPal { Email: "john@example.com" } // true: applied to payment.Value payment is { Value: PayPal } // true: applied to the union itself payment is { Email: "john@example.com" } // error CS0117: 'PaymentMethod' does not contain a definition for 'Email' payment is PaymentMethod // error CS8121: An expression of type 'PaymentMethod' cannot be handled by a pattern of type 'PaymentMethod'

The last one surprises most people. payment is PaymentMethod checks the contents of the union, and the contents are never a PaymentMethod.

3 patterns don't unwrap: the discard _, the var pattern and the not pattern. They apply to the union value itself.

Handling Null and Default

A union is a struct, so it has a default value. The default union holds nothing, and its Value is null:

csharp
PaymentMethod empty = default; Console.WriteLine(empty.Value is null); // output: True var description = empty switch { CreditCard => "card", PayPal => "paypal", BankTransfer => "bank transfer", null => "no payment method" }; // description is "no payment method"

The compiler tracks this for you. When the union may be empty, it asks you to handle null. When you create a union from a non-null value, the compiler knows Value isn't null and doesn't require the null arm.

Nullable unions work the way you would expect:

csharp
public static string DescribeOptional(PaymentMethod? payment) => payment switch { CreditCard card => $"Card ending in {card.Number[^4..]}", PayPal paypal => $"PayPal account {paypal.Email}", BankTransfer transfer => $"Bank transfer to {transfer.Iban}", null => "No payment method selected" };

For PaymentMethod?, the null pattern matches both a missing union and a union with an empty Value.

If you want to refresh the basics of switch expressions and patterns, check out my posts on switch expressions and pattern matching.

Copied

Adding Members to a Union

A union can have a body with methods and properties, just like a struct.

Here's a shipping rate that can be a flat fee, a price per kilogram, or free shipping above an order total:

csharp
public record class FlatRate(decimal Amount); public record class PerKilogram(decimal PricePerKg, decimal MinimumCharge); public record class FreeShipping(decimal MinimumOrderTotal); public union ShippingRate(FlatRate, PerKilogram, FreeShipping) { public decimal Calculate(decimal weightKg, decimal orderTotal) => this switch { FlatRate flat => flat.Amount, PerKilogram perKg => Math.Max(perKg.PricePerKg * weightKg, perKg.MinimumCharge), FreeShipping free when orderTotal >= free.MinimumOrderTotal => 0m, FreeShipping => 9.99m, _ => throw new InvalidOperationException("The shipping rate has no value.") }; public string Name => this switch { FlatRate => "Flat rate", PerKilogram => "Per kilogram", FreeShipping => "Free shipping", _ => "Unknown" }; public static ShippingRate Flat(decimal amount) => new FlatRate(amount); }

Inside the body, this switch matches on the union's contents. The _ arm handles a default union, which has no value.

The calling code reads naturally:

csharp
ShippingRate rate = new PerKilogram(PricePerKg: 2.5m, MinimumCharge: 5m); Console.WriteLine($"{rate.Name}: {rate.Calculate(weightKg: 4, orderTotal: 120m)}"); // output: Per kilogram: 10.0 var flat = ShippingRate.Flat(7.5m); Console.WriteLine($"{flat.Name}: {flat.Calculate(weightKg: 1, orderTotal: 20m)}"); // output: Flat rate: 7.5

The business logic for shipping rates lives in one place, next to the cases it works with.

Rules for Union Bodies

A union stores everything in its single Value, so the body has a few restrictions:

  • No state: Instance fields, auto-properties and field-like events aren't allowed (error CS9373).
  • No public single-parameter constructors: The compiler generates those for the case types.
  • Constructors must delegate: Any constructor you write must call a generated constructor with this(...) (error CS9375).

Static factory methods, like ShippingRate.Flat, are often a cleaner alternative to custom constructors.

Here's another popular example: an API that accepts one item or many.

csharp
public union OneOrMore<T>(T, IEnumerable<T>) { public IEnumerable<T> AsEnumerable() => this switch { T single => [single], IEnumerable<T> many => many, null => [] }; } OneOrMore<string> tag = "express"; OneOrMore<string> tags = new[] { "fragile", "insured" }; Console.WriteLine(string.Join(", ", tag.AsEnumerable())); // output: express Console.WriteLine(string.Join(", ", tags.AsEnumerable())); // output: fragile, insured

Callers pass whichever form they have, and the union hides the difference.

Copied

Closed Hierarchies

Unions are great when the cases are unrelated types. But what if your cases share a base type and some common data?

C# 15 also ships closed hierarchies for that.

You mark a class with the closed modifier. Then only code in the same assembly can derive from it directly.

Here's a shipment status:

csharp
public closed record class ShipmentStatus; public record class Pending(DateTime CreatedAt) : ShipmentStatus; public record class Dispatched(string Carrier) : ShipmentStatus; public record class InTransit(string Carrier, string TrackingNumber) : ShipmentStatus; public record class Delivered(DateTime DeliveredAt) : ShipmentStatus; public record class Cancelled(string Reason) : ShipmentStatus;

The compiler knows every direct descendant, so the switch is exhaustive without a default branch:

csharp
public static string Describe(ShipmentStatus status) => status switch { Pending(var createdAt) => $"Pending since {createdAt:yyyy-MM-dd}", Dispatched(var carrier) => $"Dispatched with {carrier}", InTransit(var carrier, var trackingNumber) => $"In transit with {carrier}, tracking {trackingNumber}", Delivered(var deliveredAt) => $"Delivered on {deliveredAt:yyyy-MM-dd}", Cancelled(var reason) => $"Cancelled: {reason}" };

Code in another assembly can't add new statuses:

csharp
// In another assembly public record class Returned(DateTime ReturnedAt) : ShipmentStatus; // Error: 'ShipmentStatus' is a closed class

Rules for Closed Classes:

  • A closed class is implicitly abstract
  • You can't combine closed with sealed, static or abstract (error CS9381)
  • Direct subtypes must be declared in the same assembly
  • The restriction isn't transitive: Delivered isn't closed, so another assembly can derive from it. Mark it sealed or closed if you want to prevent that.

Closed hierarchies work with generics. Every type parameter of a derived class must be used in the base class:

csharp
public closed record class Tree<T>; public record class Leaf<T>(T Value) : Tree<T>; public record class Branch<T>(Tree<T> Left, Tree<T> Right) : Tree<T>; public record class Constant<U>(U Value) : Tree<int>; // error CS9383: 'Constant<U>': The type parameter 'U' must be referenced // in the base type 'Tree<int>' because the base type is closed.

This rule lets the compiler match each Tree<int> with exactly one Leaf<int> and one Branch<int>.

Exhaustiveness also works for type parameters constrained to a closed type:

csharp
public static bool CanCancel<TStatus>(TStatus status) where TStatus : ShipmentStatus => status switch { Pending or Dispatched => true, InTransit or Delivered or Cancelled => false };

And when the input is nullable, the compiler asks you to handle null too:

csharp
public static string DescribeOrUnknown(ShipmentStatus? status) => status switch { null => "Unknown", Pending => "Pending", Dispatched => "Dispatched", InTransit => "In transit", Delivered => "Delivered", Cancelled => "Cancelled" };

Union or Closed Hierarchy?

  • Use a union when the cases are unrelated types: int or string, CreditCard or PayPal, a response or a list of errors.
  • Use a closed hierarchy when the cases are variations of one concept and share data or behavior through a base class.
Copied

Closed Enums: Coming Next

Enums have the same problem as open class hierarchies. Nothing stops you from writing (ShipmentPriority)42, so a switch over an enum always needs a default branch.

The C# team is working on closed enums to fix this:

csharp
public closed enum ShipmentPriority { Standard, Express, Overnight }

A closed enum only allows its declared values:

csharp
ShipmentPriority priority = 0; // OK: every closed enum has a member for 0 priority = (ShipmentPriority)1; // OK: 1 is Express priority = (ShipmentPriority)10; // Error: no member with value 10 priority = (ShipmentPriority)someInt; // Error: someInt is not a constant

And a switch over all members becomes exhaustive:

csharp
decimal surcharge = priority switch { ShipmentPriority.Standard => 0m, ShipmentPriority.Express => 9.99m, ShipmentPriority.Overnight => 24.99m };

Note: Closed enums are not part of C# 15. They're an active proposal (csharplang #9011) in the language team's working set, and the syntax may change before they ship.

Together, these 3 features give C# a complete exhaustiveness story:

  • Union types for unrelated cases
  • Closed hierarchies for related cases
  • Closed enums for named constants
Copied

Unions in System.Text.Json

System.Text.Json in .NET 11 supports unions out of the box.

The serializer writes the active case directly, without a wrapper object or a $type field:

csharp
OrderReference byId = 42; OrderReference byNumber = "EXT-1042"; Console.WriteLine(JsonSerializer.Serialize(byId)); // output: 42 Console.WriteLine(JsonSerializer.Serialize(byNumber)); // output: "EXT-1042"

When deserializing, the serializer picks the case from the JSON token type. A number becomes the int case and a string becomes the string case:

csharp
var fromNumber = JsonSerializer.Deserialize<OrderReference>("42"); var fromString = JsonSerializer.Deserialize<OrderReference>("\"EXT-1042\""); Console.WriteLine(fromNumber.Value is int); // output: True Console.WriteLine(fromString.Value is string); // output: True

But what about a union of two record types? Both are JSON objects, so the token type isn't enough.

For this case, use the built-in structural classifier. It picks the case by the property names in the JSON:

csharp
public sealed record CardDetails(string Number, string Holder); public sealed record PayPalDetails(string Email); [JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))] public union CustomerPayment(CardDetails, PayPalDetails); var payment = JsonSerializer.Deserialize<CustomerPayment>("""{"Email":"john@example.com"}"""); Console.WriteLine(payment.Value); // output: PayPalDetails { Email = john@example.com }

The Email property only exists on PayPalDetails, so that case wins. If the JSON matches zero or several cases, the serializer throws a JsonException.

Closed hierarchies get a nice upgrade as well. System.Text.Json can now infer all derived types, so you don't need a [JsonDerivedType] attribute for each one:

csharp
[JsonPolymorphic(InferClosedTypePolymorphism = true)] public closed record class ShipmentStatus; ShipmentStatus status = new InTransit("DHL", "JD014600006281234567"); var json = JsonSerializer.Serialize(status); // {"$type":"InTransit","Carrier":"DHL","TrackingNumber":"JD014600006281234567"} var restored = JsonSerializer.Deserialize<ShipmentStatus>(json); Console.WriteLine(restored is InTransit); // output: True
Copied

Unions in ASP.NET Core

Because ASP .NET Core uses System.Text.Json, unions work everywhere JSON is used.

Returning Outcomes from Handlers

My favorite use case is returning one of several outcomes from a handler, instead of throwing exceptions.

Here's a handler that creates a shipment for an order:

csharp
public sealed record CreateShipmentRequest(int OrderId, string Carrier); public sealed record ShipmentCreated(string Number, int OrderId, string Carrier); public sealed record OrderNotFound(int OrderId); public sealed record ShipmentAlreadyExists(int OrderId, string Number); public union CreateShipmentResult(ShipmentCreated, OrderNotFound, ShipmentAlreadyExists); public sealed class CreateShipmentHandler(AppDbContext dbContext) { public async Task<CreateShipmentResult> HandleAsync( CreateShipmentRequest request, CancellationToken cancellationToken) { var orderExists = await dbContext.Orders.AnyAsync(o => o.Id == request.OrderId, cancellationToken); if (!orderExists) { return new OrderNotFound(request.OrderId); } var existing = await dbContext.Shipments .FirstOrDefaultAsync(s => s.OrderId == request.OrderId, cancellationToken); if (existing is not null) { return new ShipmentAlreadyExists(request.OrderId, existing.Number); } var shipment = new Shipment { Number = $"SHP-{request.OrderId:D5}", OrderId = request.OrderId, Carrier = request.Carrier }; dbContext.Shipments.Add(shipment); await dbContext.SaveChangesAsync(cancellationToken); return new ShipmentCreated(shipment.Number, shipment.OrderId, shipment.Carrier); } }

The method signature tells you every possible outcome. Thanks to implicit conversions, each return is a plain record.

The endpoint maps each outcome to an HTTP response:

csharp
app.MapPost("/shipments", async ( CreateShipmentRequest request, CreateShipmentHandler handler, CancellationToken cancellationToken) => { var result = await handler.HandleAsync(request, cancellationToken); return result switch { ShipmentCreated created => Results.Created($"/shipments/{created.Number}", created), OrderNotFound notFound => Results.NotFound($"Order {notFound.OrderId} was not found"), ShipmentAlreadyExists exists => Results.Conflict($"Order {exists.OrderId} already has shipment {exists.Number}") }; });

Calling the endpoint twice for the same order returns 201 Created, then 409 Conflict. An unknown order returns 404 Not Found.

If you add a new outcome to CreateShipmentResult, the endpoint stops compiling cleanly until you map it.

Unions in Request and Response Bodies

Unions work in request bodies:

csharp
app.MapPost("/payments/preview", (CustomerPayment payment) => payment switch { CardDetails card => $"Charge card ending in {card.Number[^4..]} for {card.Holder}", PayPalDetails paypal => $"Redirect to PayPal for {paypal.Email}" });

A body with {"email":"john@example.com"} returns "Redirect to PayPal for john@example.com".

And in responses:

csharp
app.MapGet("/orders/{id:int}/reference", async (int id, AppDbContext dbContext, CancellationToken cancellationToken) => { var order = await dbContext.Orders.FindAsync([id], cancellationToken); return order is null ? Results.NotFound() : TypedResults.Ok(order.Reference); }) .Produces<OrderReference>();

This endpoint returns 1001 for one order and "EXT-1042" for another.

OpenAPI Support

ASP .NET Core 11 describes unions in OpenAPI 3.2 documents with an anyOf schema. Here's what the generated document contains for CustomerPayment:

json
"CustomerPayment": { "type": "object", "anyOf": [ { "$ref": "#/components/schemas/CardDetails" }, { "$ref": "#/components/schemas/PayPalDetails" } ] }

Unlike polymorphic types, union cases don't need a $type discriminator, so each case reuses its own schema.

Limitations:

  • Unions work for JSON bodies only. Route values, query strings, headers and form fields can't bind to a union.
  • SignalR supports unions with the JSON hub protocol only. MessagePack and Newtonsoft.Json don't support them.
  • Blazor supports unions in JavaScript interop, persistent component state and prerendered component parameters.
Copied

Making Your Result Type Union-Aware

Many .NET projects already return results instead of throwing exceptions. I explained this approach in detail in my post on how to replace exceptions with the Result pattern.

In my projects, I use my own Result<TValue> type. It works like OneOf, ErrorOr or FluentResults, but it fits my code better.

Here's a simplified version:

csharp
public readonly partial record struct Result<TValue> { private Result(TValue value) => Value = value; private Result(Error error) => Errors = [error]; private Result(List<Error> errors) => Errors = errors; public bool IsSuccess => Errors is null or []; public bool IsError => Errors.Count > 0; public List<Error> Errors { get; } = []; public TValue? Value { get { if (IsError) { throw new InvalidOperationException("Check IsSuccess or IsError before accessing the Value."); } return field; } } public static implicit operator Result<TValue>(TValue value) => new(value); public static implicit operator Result<TValue>(Error error) => new(error); public static implicit operator Result<TValue>(List<Error> errors) => new(errors); }

And this is how an endpoint consumes it:

csharp
var result = await handler.HandleAsync(number, cancellationToken); if (result.IsError) { return result.Errors.ToProblem(); } return Results.Ok(result.Value);

Nothing forces you to check IsError. Forget the check, and result.Value throws at runtime.

C# 15 lets existing types opt into union behavior. You don't need to rewrite Result<TValue> with the union keyword.

Add the [Union] attribute and a union member provider:

csharp
[Union] public readonly record struct Result<TValue> : Result<TValue>.IUnionMembers { // Constructors, IsSuccess, IsError, Errors, Value and implicit operators stay the same public interface IUnionMembers { static Result<TValue> Create(TValue value) => new(value); static Result<TValue> Create(List<Error> errors) => new(errors); object? Value { get; } } object? IUnionMembers.Value => IsError ? Errors : Value; }

The nested IUnionMembers interface tells the compiler how to treat Result<TValue> as a union:

  • Create methods define the case types: TValue and List<Error>. They can call the private constructors because the interface is nested inside the struct.
  • Value property returns the current case. It's implemented explicitly, so the public TValue? Value property keeps working as before.

Your existing implicit operators still win over union conversions. So return ShipmentErrors.NotFound(number); compiles exactly as it did before.

Now the endpoint can match on the result:

csharp
app.MapGet("/shipments/{number}", async ( string number, GetShipmentHandler handler, CancellationToken cancellationToken) => { var result = await handler.HandleAsync(number, cancellationToken); return result switch { ShipmentResponse shipment => Results.Ok(shipment), List<Error> errors => errors.ToProblem() }; });

The switch is exhaustive with 2 cases and no default branch. There's no IsError check to forget, and no Value access that can throw.

The handler doesn't change at all:

csharp
public async Task<Result<ShipmentResponse>> HandleAsync(string number, CancellationToken cancellationToken) { if (!number.StartsWith("SHP-", StringComparison.Ordinal)) { return ShipmentErrors.InvalidNumber(number); } var shipment = await dbContext.Shipments .AsNoTracking() .FirstOrDefaultAsync(s => s.Number == number, cancellationToken); if (shipment is null) { return ShipmentErrors.NotFound(number); } return new ShipmentResponse(shipment.Number, shipment.OrderId, shipment.Carrier); }

A request for SHP-00001 returns 200 OK, SHP-404 returns 404 Not Found, and ABC returns 400 Bad Request with the validation error.

Note: Error isn't a case type here, even though there's an implicit conversion from it. A single Error is stored as a list, and a union's Value must always match the case it was created from.

Library authors can use the same trick. OneOf, ErrorOr, FluentResults and other result libraries can add [Union] support without breaking their existing APIs.

Copied

Custom Unions and Performance

The union keyword generates a struct with a single object? field. That's simple and compact, but it has a cost: value-type cases are boxed.

Every time you store an int or a decimal in a union, the runtime allocates a small object on the heap.

For most code, this doesn't matter. For hot paths, you can write a custom union that stores values without boxing:

csharp
[Union] public readonly struct Quantity : IUnion { private readonly int _units; private readonly decimal _kilograms; private readonly byte _tag; // 0 = none, 1 = units, 2 = kilograms public Quantity(int units) { _units = units; _tag = 1; } public Quantity(decimal kilograms) { _kilograms = kilograms; _tag = 2; } public object? Value => _tag switch { 1 => _units, 2 => _kilograms, _ => null }; public bool HasValue => _tag != 0; public bool TryGetValue(out int units) { units = _units; return _tag == 1; } public bool TryGetValue(out decimal kilograms) { kilograms = _kilograms; return _tag == 2; } }

Any struct or class with the [Union] attribute, public single-parameter constructors and a Value property is a union.

The HasValue property and the TryGetValue methods form the non-boxing access pattern. When they exist, the compiler uses TryGetValue for type patterns and HasValue for null checks, instead of reading the boxed Value.

Pattern matching looks exactly the same as with a generated union:

csharp
public static string Describe(Quantity quantity) => quantity switch { int units => $"{units} pcs", decimal kilograms => $"{kilograms} kg" }; Quantity units = 12; Quantity weight = 2.5m; Console.WriteLine(Describe(units)); // output: 12 pcs Console.WriteLine(Describe(weight)); // output: 2.5 kg

I compared it with union BoxedQuantity(int, decimal) in BenchmarkDotNet, creating and matching 1,000 values:

MethodMeanAllocated
GeneratedUnion5.416 us28,000 B
NonBoxingUnion3.586 us-

The non-boxing union is 34% faster and allocates nothing. The generated union allocates 28 bytes per value on average: 24 bytes for a boxed int and 32 bytes for a boxed decimal.

Note: Measured on .NET 11 with BenchmarkDotNet 0.15.8 (in-process toolchain), Apple Silicon. Your numbers will vary.

Class-Based Unions

A union can also be a class when you need reference semantics:

csharp
[Union] public sealed class ShipmentLookup : IUnion { public ShipmentLookup(Shipment shipment) => Value = shipment; public ShipmentLookup(ShipmentNotFound notFound) => Value = notFound; public object? Value { get; } } public static string Describe(ShipmentLookup? lookup) => lookup switch { Shipment shipment => $"{shipment.Number} ships with {shipment.Carrier}", ShipmentNotFound notFound => $"Shipment {notFound.Number} not found", null => "No lookup" };

For class-based unions, null matches both a null reference and a null Value.

Every union implements IUnion, so you can also detect unions at runtime, for example in logging or serialization code:

csharp
object boxed = (PaymentMethod)new PayPal("john@example.com"); if (boxed is IUnion { Value: PayPal paypal }) { Console.WriteLine($"Union with PayPal {paypal.Email}"); }
Copied

Unions and EF Core

EF Core 11 doesn't map union types out of the box. But you have 2 good options today.

Option 1: Closed Hierarchy with TPH

If your cases are entities, model them as a closed hierarchy and map it with table-per-hierarchy (TPH):

csharp
public closed class Payment { public int Id { get; set; } public int OrderId { get; set; } public decimal Amount { get; set; } } public sealed class CardPayment : Payment { public required string CardLast4 { get; set; } } public sealed class PayPalPayment : Payment { public required string Email { get; set; } } public sealed class BankTransferPayment : Payment { public required string Iban { get; set; } }
csharp
modelBuilder.Entity<Payment>(builder => { builder.HasDiscriminator<string>("Method") .HasValue<CardPayment>("Card") .HasValue<PayPalPayment>("PayPal") .HasValue<BankTransferPayment>("BankTransfer"); builder.Property(p => p.Amount).HasPrecision(18, 2); });

EF Core stores all payments in one Payments table with a Method discriminator column. A closed class is implicitly abstract, and EF Core handles abstract base types in TPH without any extra configuration.

When you load payments, the mapping code is exhaustive:

csharp
private static PaymentResponse ToResponse(Payment payment) => payment switch { CardPayment card => new(card.Id, card.OrderId, card.Amount, "Card", $"**** {card.CardLast4}"), PayPalPayment paypal => new(paypal.Id, paypal.OrderId, paypal.Amount, "PayPal", paypal.Email), BankTransferPayment bank => new(bank.Id, bank.OrderId, bank.Amount, "Bank transfer", bank.Iban) };

Add a fourth payment type, and the compiler points you to this method.

Option 2: Value Converter for Small Unions

For a small value union like OrderReference, a value converter stores it in a single column:

csharp
public sealed class OrderReferenceConverter() : ValueConverter<OrderReference, string>( reference => ToDatabase(reference), value => FromDatabase(value)) { private const string IdPrefix = "id:"; private const string NumberPrefix = "ext:"; private static string ToDatabase(OrderReference reference) => reference switch { int id => $"{IdPrefix}{id}", string number => $"{NumberPrefix}{number}", null => throw new InvalidOperationException("Order reference has no value.") }; private static OrderReference FromDatabase(string value) => value.StartsWith(IdPrefix, StringComparison.Ordinal) ? new OrderReference(int.Parse(value[IdPrefix.Length..])) : new OrderReference(value[NumberPrefix.Length..]); }
csharp
modelBuilder.Entity<Order>() .Property(o => o.Reference) .HasConversion<OrderReferenceConverter>() .HasMaxLength(50);

The Reference column contains values like id:1001 and ext:EXT-1042. The prefix tells the converter which case to restore.

The conversion logic sits in static methods because EF Core value converters are expression trees, and expression trees can't contain switch expressions.

Note: EF Core can't translate pattern matching on a converted union into SQL. If you need to filter by case, prefer the TPH approach.

Copied

Best Practices for Union Types

Copied

Choose the Right Tool

Unions, closed hierarchies, enums and result types overlap. Here's how I choose:

  • Union: a value is one of several unrelated types, like int or string, or a set of handler outcomes.
  • Closed hierarchy: the cases are related and share data or behavior through a base class, or you store them with EF Core.
  • Enum: the cases are plain named constants without data.
  • Result type: you need success or failure with a list of errors and helper methods. Make it union-aware to get exhaustive matching.
Copied

Name Cases After Outcomes

Small, focused records make the best case types:

csharp
// Good: each case says what happened public sealed record OrderCancelled(int OrderId, DateTime CancelledAt); public sealed record OrderNotFound(int OrderId); public sealed record OrderAlreadyShipped(int OrderId, string ShipmentNumber); public union CancelOrderResult(OrderCancelled, OrderNotFound, OrderAlreadyShipped); // Bad: callers have to guess what a string or an int means public union CancelOrderResult(Order, string, int);

With named cases, the switch in your endpoint reads like a list of business rules.

Copied

Watch Value-Type Cases on Hot Paths

Generated unions box int, decimal, Guid and other value types. That's fine for request handling. For tight loops that process millions of values, write a custom union with the non-boxing access pattern.

Copied

Treat New Cases as an API Change

Adding a case to a public union breaks every consumer's exhaustive switch. Inside your own code, that's exactly what you want. In a NuGet package, it's a breaking change that deserves a major version.

Copied

Keep Unions in JSON Bodies

ASP .NET Core can't bind unions from routes, query strings or headers. Use simple types for those and keep unions in request and response bodies.

Copied

Summary

Union types are the C# feature I've been waiting for the most.

I've been playing around with them for more than a week. I have really enjoyed the little time I spent writing some code by hand. What a pleasure!

  • Unions let a value be exactly one of a fixed set of types, with implicit conversions from each case.
  • Exhaustive pattern matching turns a missing case into a compiler warning instead of a production bug.
  • Closed hierarchies bring the same checks to class hierarchies, and closed enums are coming next.
  • System.Text.Json and ASP .NET Core support unions in JSON bodies and OpenAPI documents.
  • Existing types, like your own Result<TValue>, can become unions with [Union] and a union member provider.
  • Custom unions with TryGetValue avoid boxing on hot paths.

Start with the union keyword for handler results and payment-style alternatives. Reach for custom unions only when you measure a real performance problem.

If you want to learn more about .NET 11 and C# 15 features, I recommend checking this article.

Hope you find this newsletter useful. See you next time.

Whenever you're ready, here's how I can help you:

The .NET Senior Playbook is built to:

  • Fast-track you from junior or mid-level to senior
  • Keep you growing as a senior
  • Help you beat any .NET interview

Covers everything: C#, ASP.NET Core, EF Core, system design — answer each question first, reveal the solution, and a test after every chapter proves it stuck. Finish, and you earn a verifiable certificate for your LinkedIn.

The .NET Senior Playbook
Join 500+ developers

Not sure where you stand? Take the free .NET interview test:

  • Find out your real level — Junior to Senior+
  • A realistic mock .NET interview — across 13 areas of C#, .NET, ASP.NET Core and System Design

No credit card required. When you finish, you get a personalized report: your level, your strongest and weakest areas, and where to focus next — the perfect way to benchmark yourself before diving into the Playbook.

Start the free test

Master .NET and Software Architecture,
so AI can't replace you

Real-world architecture judgment, production trade-offs, and .NET in depth — the things that keep you relevant in the job market.

Plus a free PDF: 200 senior .NET interview questions on C#, ASP.NET Core, EF Core & System Design.

Join 28,000+ developers already reading
No spam. Unsubscribe any time.
You can download source code for this newsletter for free
Download source code

Enjoyed this article? Share it with your network