C# 15 Union Types Explained: One Value, Several Types
Sometimes a value can be one of several different kinds of thing. A union type writes down exactly which kinds, and the compiler makes sure you never forget to handle one.
Think about a method that places an order. It can end in three very different ways: the order was created, the product was out of stock, or the requested quantity was invalid. Each outcome carries different information: an order number, a product name, a bad number.
Before C# 15, every way of returning "one of these three things" had a catch. Return object, and the compiler can't help you. Throw exceptions, and normal outcomes start looking like crashes. Create an abstract base class, and every outcome has to inherit from it, which built-in types such as int and string can't do.
In this lesson, you'll learn how C# 15 union types solve this: how to declare one, how to put a value in it, how to read it back safely with a switch the compiler checks for you, and what to watch out for with null and default values.
What Is It?
The Simple Explanation
A union is a type whose value is exactly one of a fixed list of other types. You declare it with the union keyword and list the allowed types in brackets:
public record class Cat(string Name);
public record class Dog(string Name);
public record class Bird(string Name);
public union Pet(Cat, Dog, Bird);Read it as: "a Pet is a Cat, or a Dog, or a Bird." The listed types are called the case types. A Pet variable always holds one of them (or nothing, as you'll see later), and whenever you switch on a Pet, the compiler checks that you handled all three.
The Technical Definition
A union declaration names a type and a list of case types. Case types can be any type that converts to object: classes, records, structs, interfaces, type parameters, nullable types, even other unions. The language provides an implicit union conversion from each case type to the union. Type patterns applied to a union test its contents, and a switch expression that handles every case type is exhaustive. The compiler turns the declaration into a struct that holds the contents in a Value property of type object?.
Before C# 15
- Return object and cast later, with no compiler help
- Or create an abstract base class every outcome must inherit from
- Built-in types like int and string can't join a base class
- A switch usually needs a _ => default arm "just in case"
With C# 15 union types
- public union Result(Created, OutOfStock, InvalidQuantity);
- Any existing types can be cases, including int and string
- Each case type converts to the union automatically
- A switch that handles every case needs no default arm
Why Does It Exist?
The Problem — "One of These" Had No Name
Programs are full of "one of several" situations: a payment is card, cash or voucher; a setting is a number or a piece of text; a message is a login, a logout or a chat line. Until C# 15, the language had no direct way to say that. You either gave up type safety (object) or forced the types into an inheritance tree (an abstract base class), even when they had nothing in common.
The Solution — List the Cases, Let the Compiler Check
A union names the situation directly. Because the full list of case types is written in the declaration, the compiler knows every possibility. If you add a fourth case later, every switch that forgot it gets a warning, so you find the gaps at compile time instead of in production.
Big Picture
How It Works
public union Pet(Cat, Dog, Bird);- Pet pet = new Dog("Rex"); uses the implicit union conversion. Behind the scenes the compiler calls a generated constructor that takes a Dog.
- The Dog is now stored in pet.Value. The union holds exactly one value at a time.
- Type patterns such as Dog d test the contents, not the union itself. The first matching arm runs.
- Because Pet lists exactly Cat, Dog and Bird, a switch that handles all three is complete. Miss one and you get a warning.
Simple Example
Here is a union whose cases are two built-in types: a number or a piece of text. Notice that int and string don't share a base class you control, which is exactly the situation unions are built for.
IntOrString age = 42; // union conversion from int
IntOrString name = "Priya"; // union conversion from string
Console.WriteLine(Describe(age)); // Number: 42
Console.WriteLine(Describe(name)); // Text: Priya
static string Describe(IntOrString value) => value switch
{
int number => $"Number: {number}",
string text => $"Text: {text}",
};
public union IntOrString(int, string);Code → Meaning → Result: age holds an int and name holds a string, but both have the same type, IntOrString. Inside Describe, the switch tests the contents. Because both case types are handled, the compiler is satisfied without a _ => arm. (In a Program.cs file the union declaration goes at the bottom, after the top-level statements.)
Real-World Example
Back to the order method from the start of the lesson. Each outcome is a small record, and the union lists all three:
public record class Created(int OrderId);
public record class OutOfStock(string ProductName);
public record class InvalidQuantity(int Requested);
public union PlaceOrderResult(Created, OutOfStock, InvalidQuantity);
public class OrderService
{
private readonly Dictionary<string, int> _stock = new() { ["Keyboard"] = 3 };
private int _nextId = 1;
public PlaceOrderResult PlaceOrder(string product, int quantity)
{
if (quantity <= 0)
return new InvalidQuantity(quantity);
if (!_stock.TryGetValue(product, out int available) || available < quantity)
return new OutOfStock(product);
_stock[product] = available - quantity;
return new Created(_nextId++);
}
}Each return hands back a different record, and each one converts to PlaceOrderResult automatically. The caller can't forget an outcome:
var service = new OrderService();
PlaceOrderResult result = service.PlaceOrder("Keyboard", 2);
string message = result switch
{
Created c => $"Order {c.OrderId} placed.",
OutOfStock o => $"Sorry, {o.ProductName} is out of stock.",
InvalidQuantity q => $"{q.Requested} is not a valid quantity.",
};
Console.WriteLine(message); // Order 1 placed.Unions also work with System.Text.Json in .NET 11. The serializer writes the active case directly, with no wrapper object and no $type field:
public union Reading(int, string);
Reading reading = new("hello");
string json = JsonSerializer.Serialize(reading);
Console.WriteLine(json); // "hello"A Reading holding 42 is written as 42. ASP.NET Core 11 uses the same support, so a minimal API endpoint can return a union and the generated OpenAPI document lists each case. Unions can't be read from route values, query strings, headers or form fields, though, only from JSON bodies.
Analogy
Picture a box with a label on the lid: "Contains ONE of: a cat, a dog, a bird." You can't put a fish in it, because the label doesn't allow it. And whoever opens the box must be ready for any of the three animals, because the label says any of them might be inside.
The union declaration is the label. The switch is the person opening the box. The compiler checks that this person is prepared for every animal on the label.
Under the Hood
- It becomes a struct. The compiler turns union Pet(...) into a struct marked with the [Union] attribute and implementing the IUnion interface. Both types live in System.Runtime.CompilerServices and ship with the .NET 11 runtime.
- **One constructor per case type, plus Value.** The struct gets a public constructor for each case type and a Value property of type object?. The implicit conversions simply call those constructors.
- Value-type cases are boxed. Because the contents are stored as object?, a case such as int is boxed when it goes in. Advanced users can write custom union types that avoid this, but the generated form always boxes.
- You can add members, with limits. A union can have a body with methods and computed properties, like a struct, but it can't declare instance fields, auto-properties or field-like events.
Common Confusion
1. "A union is like a record with several fields" — no, it holds exactly one value
A record with three properties holds three things at once. A union holds one thing, which can be any one of its case types. Unions also don't add equality, cloning or deconstruction the way records do; their whole job is answering "which case is it?"
2. "pet is Pet checks whether I have a pet" — no, patterns look inside
Type patterns on a union test its contents. None of Cat, Dog or Bird is a Pet, so pet is Pet is a compile error (CS8121). To check that a union holds something, write pet is not null.
3. "A union variable always holds one of its cases" — not when it's default
Because a union is a struct, default creates one with nothing inside: Value is null. That happens for uninitialized fields and new array elements. A switch with no null arm throws a SwitchExpressionException when it receives such a value.
Pet pet = default;
string description = pet switch
{
Dog d => d.Name,
Cat c => c.Name,
Bird b => b.Name,
null => "no pet", // handles the empty default value
};
Console.WriteLine(description); // no petCommon Mistakes
Mistake 1 — Ending every switch with a discard arm
The mistake: Adding _ => "unknown" to a switch over a union "to be safe". Later someone adds a fourth case type, and the discard silently swallows it, so the compiler can no longer warn you.
The fix: List every case type explicitly. If empty values can reach the switch, add a null arm rather than _. The null arm handles the empty case and still lets the compiler warn about any new case type.
Mistake 2 — Expecting unions in query strings
The mistake: Declaring a minimal API parameter like [FromQuery] IntOrString id and expecting ASP.NET Core to fill it in.
The fix: Unions are supported wherever System.Text.Json reads or writes, such as request and response bodies. Route values, query strings, headers and form fields can't bind to a union, so use an ordinary type there.
When Should I Use It?
- Result-or-error returns: a method that returns either a success value or one of several failure values.
- Message or command handling: a fixed set of message types, where adding a new one should flag every switch that doesn't handle it yet.
- Replacing marker interfaces or abstract classes that exist only to group types for pattern matching.
- Not when the types share behaviour you want to call directly. That's what interfaces and base classes are for. And if the cases are records you write yourself and want them to share members, consider the closed hierarchies in the next lesson.
Mental Model
Put a value in: Pet pet = new Dog(...). Take it out: pet switch { Dog d => ... }.
Patterns look at the contents. A default union is empty, so add a null arm when that can happen.
Remember: a union is a labelled box that holds exactly one item from the label's list, and the compiler checks you're ready for every item on it.
Key Takeaway
- C# 15's union keyword declares a type whose value is exactly one of a fixed list of case types: public union Pet(Cat, Dog, Bird);.
- Each case type converts to the union automatically, so Pet pet = new Dog("Rex"); just works.
- Type patterns test the contents, and a switch that handles every case type is exhaustive, with no default arm needed.
- The compiler generates a struct with a Value property (object?). A default union has Value == null, so handle null when it can reach your code.
- System.Text.Json and ASP.NET Core 11 understand unions in JSON bodies; route values, query strings, headers and forms can't bind to them.
Check Your Understanding
Let's check the three ideas that matter most: conversion, exhaustive switches, and the empty default.
1. Given public union Pet(Cat, Dog, Bird);, what happens on the line Pet pet = new Dog("Rex");?
Show answer
Correct: B
Why B is correct: C# 15 provides an implicit union conversion from each case type. It calls the generated constructor, and the Dog becomes the union's contents.
Why A is incorrect: This is exactly the conversion unions provide. Any listed case type converts to the union automatically.
Why C is incorrect: Unions don't use inheritance. Dog stays an ordinary record, and the union simply lists it as a case type.
Why D is incorrect: The same Dog instance is stored in Value. Nothing is copied into a different kind of object.
Reinforcement: Assigning a case type to a union = an automatic union conversion into Value.
2. A switch expression over a Pet has arms for Dog, Cat and Bird, and no _ arm. What does the compiler do?
Show answer
Correct: B
Why B is correct: The compiler knows the complete list of case types from the declaration, so handling all three makes the switch exhaustive.
Why A is incorrect: Switch expressions only need a default arm when the compiler can't prove every possibility is covered. With a union, it can.
Why C is incorrect: Pet isn't one of its own case types. Patterns test the contents, which are always a Dog, Cat or Bird.
Why D is incorrect: The compiler never invents arms for you. A value that matches no arm at runtime throws a SwitchExpressionException.
Reinforcement: List every case type and the switch is complete, with nothing hidden.
3. What is in pet.Value after Pet pet = default;, and why does it matter?
Show answer
Correct: B
Why B is correct: A union is a struct, and its default value has nothing inside: Value is null. A switch that only handles the three case types throws when it receives it, so add a null arm wherever default values can appear.
Why A is incorrect: The compiler never picks a case for you. A default union is simply empty.
Why C is incorrect: default is allowed for any struct, including unions. That's exactly why the empty case exists.
Why D is incorrect: No case value is created. The contents are null.
Reinforcement: Default union = empty union. Handle null when defaults can reach your switch.
Unions group types that don't share anything. The next lesson covers the other half of the story: closed hierarchies, for when the possible types are your own subclasses and you want the compiler to know there will never be any others.