All the code in this series is available on GitHub. Clone it, run it, and try breaking it yourself.

GitHub logo georgekobaidze / dotnet11-playground

A lightweight playground repository for experimenting with and testing new features introduced in .NET 11 and C# 15.

.NET 11 & C# 15 Playground

.NET 11 & C# 15 Playground

A lightweight playground repository for experimenting with and testing new features introduced in .NET 11 and C# 15.

Use it to explore language changes, try out APIs, and validate ideas in isolation without production constraints. Each feature lives in its own small project, often with a "before" and "after" version so you can see what the new feature actually changes.

What's inside

Project Feature Description
Unions Union types A small console login flow that compares the classic class-hierarchy approach with C# 15 unions and compiler-checked exhaustive matching.

More examples will be added as new features are explored.

Getting started

You'll need the .NET 11 SDK. Then clone the repo and run any example:

dotnet run --project src/Unions

Disclaimer

.NET 11 and C# 15 features may still change. The code here is for learning and experimentation, not production use.




Follow me on GitHub for more updates!

Table of Contents

  • The Impossible Branch
  • What Is a Union, Anyway?
    • A Union Is a List of Existing Types
    • Case Types Convert to the Union Automatically
    • Pattern Matching Looks Inside
    • The Current Case Lives in Value
    • Cases Don't Have to Be Related, or Even Yours
    • The Vocabulary
  • C# Is Late to This Party
  • Before and After: Logging In
    • Before C# 15: The Abstract Base Record
    • After C# 15: A Union
  • How C# Unions Actually Work
    • Declaring a Union
    • Pattern Matching Unwraps for You
  • Do We Actually Need Them?
    • The Case for Unions
    • The Case Against (Or at Least, for Caution)
    • My Take
  • Wrapping Up

The Impossible Branch

_ => throw new InvalidOperationException("Unsupported type")

Does this piece of code look familiar to you? I bet it does.

Sometimes it ends up being a serious problem. Someone adds a new case, the compiler stays quiet, and the "impossible" branch runs.

For years, we worked around this with abstract base classes, marker interfaces, and libraries like OneOf. They all worked, well... kind of. None of them let the compiler say: "this value is exactly one of these types, and you forgot one."

With .NET 11, released on November 10, 2026, that changes. C# 15 ships with a union keyword, and it's no longer a preview feature. In this article, we'll look at what unions are, where they come from, how they work in C#, and whether you should actually use them.

What Is a Union, Anyway?

A union is a type whose value is EXACTLY one of a fixed set of options. Not two at once, not something outside the list.

Traffic lights

Think of a traffic light. It's red, yellow, or green. It's never red and green at the same time, and it's never purple. If you write code that reacts to a traffic light, you want someone to warn you when you forget about yellow.

A C# 15 union is a type that holds exactly one value from a fixed list of case types.

A Union Is a List of Existing Types

public record Cat(string Name); public record Dog(string Name); public union Pet(Cat, Dog); 

Pet is the union type. Cat and Dog are its case types. They're ordinary records that you can use on their own, and they don't inherit from Pet or from each other.

Case Types Convert to the Union Automatically

Pet pet = new Dog("Max"); // implicit conversion from Dog pet = new Cat("Ruby"); // now it holds a Cat // Pet other = "Max"; // error: string is not a case type of Pet 

A union holds one case at a time. Assigning a new value replaces the old one, and only the listed case types are accepted.

Pattern Matching Looks Inside

string greeting = pet switch { Dog d => $"Good boy, {d.Name}!", Cat c => $"Hello, {c.Name}." }; 

Dog d tests the value stored inside the union, so you never unwrap it yourself. And because the list of cases is fixed, the switch is complete without a _ arm.

The Current Case Lives in Value

Console.WriteLine(pet.Value); // Cat { Name = Ruby } 

Every union has a Value property of type object? that holds the current case. You'll rarely touch it directly, because pattern matching reads it for you.

Cases Don't Have to Be Related, or Even Yours

public union IntOrString(int, string); IntOrString id = 42; id = "ACME-77"; 

A case type can be almost anything: built-in types, types from other libraries, interfaces, generic type parameters, even other unions. No shared base type is required.

The Vocabulary

Term Meaning
Union type The type declared with union, for example Pet
Case type One of the types in the list, for example Cat or Dog
Union conversion The implicit conversion from a case type to the union
Value The property that holds the current case, typed object?
Exhaustive switch A switch that handles every case type, so no _ arm is needed

In one sentence: a union tells the compiler what a value can be, and the compiler makes sure you handle every option.

C# Is Late to This Party

Unions have been on the C# wishlist for a very long time. They went through years of proposals and design meetings, landed in .NET 11 Preview 2 in early 2026, and are now stable.

Most modern languages already have some form of sum type. Languages borrow good ideas from each other all the time, so it was only a matter of time before C# picked this one up. Because better late than never as they say.

Before and After: Logging In

Let's take an example everyone has seen: a login. A login attempt has three possible outcomes:

  • The user is logged in, and we get their user name.
  • The user name or password is wrong, and we get the number of attempts left.
  • The account is locked, and we get the time it unlocks.

Before C# 15: The Abstract Base Record

This is the commonly used pattern:

public abstract record LoginResult; public sealed record LoggedIn(string UserName) : LoginResult; public sealed record InvalidCredentials(int AttemptsLeft) : LoginResult; public sealed record AccountLocked(DateTimeOffset Until) : LoginResult; public class AuthService { private const int MaxAttempts = 3; private readonly Dictionary<string, string> _passwords = new() { ["ada"] = "IWroteCodeBeforeComputersExisted", ["linus"] = "TalkIsCheapShowMeTheCode", }; private readonly Dictionary<string, int> _failedAttempts = new(); public LoginResult Login(string userName, string password) { int failed = _failedAttempts.GetValueOrDefault(userName); if (failed >= MaxAttempts) return new AccountLocked(DateTimeOffset.Now.AddMinutes(15)); bool userExists = _passwords.TryGetValue(userName, out string? expectedPassword); if (!userExists || expectedPassword != password) { _failedAttempts[userName] = ++failed; return new InvalidCredentials(MaxAttempts - failed); } _failedAttempts.Remove(userName); return new LoggedIn(userName); } } 

And a console app that uses it. It keeps asking for credentials until you press Ctrl+C:

var authService = new AuthService(); while (true) { Console.Write("User name: "); string? userName = Console.ReadLine(); Console.Write("Password: "); string? password = Console.ReadLine(); if (userName is null || password is null) break; // the input stream was closed (Ctrl+Z on Windows, Ctrl+D on macOS/Linux) LoginResult result = authService.Login(userName, password); string message = result switch { LoggedIn l => $"Welcome back, {l.UserName}!", InvalidCredentials c => $"Wrong user name or password. {c.AttemptsLeft} attempts left.", AccountLocked a => $"Too many attempts. Try again after {a.Until:t}.", _ => throw new UnreachableException("Unknown error") }; Console.WriteLine(message); Console.WriteLine(); } 

It works. But look at that last arm. The compiler has no idea that LoginResult has only three subtypes.

With Discard Arm

Anyone, in any assembly, can write record LoggedOut : LoginResult. So the compiler gives us a fair warning to add a discard arm, and the discard arm swallows every case we forget.

Without Discard Arm

Now imagine that six months later, the security team adds two-factor authentication:

public sealed record TwoFactorRequired(string Method) : LoginResult; // In AuthService: private readonly HashSet<string> _twoFactorUsers = ["linus"]; // In Login, right after the password check succeeds: if (_twoFactorUsers.Contains(userName)) return new TwoFactorRequired("Authenticator app"); 

The project compiles with zero warnings. The first user who turned on two-factor types the correct password, and the whole app crashes with an UnreachableException instead of asking for a code. It turns out it was reachable.

There are other small costs too:

  • Every case type must inherit from LoginResult. You can't use types you don't own, like string or Exception.
  • The base class exists only to group things. It has no behavior.
  • The same record can't easily belong to two different groups.

After C# 15: A Union

Here's the same code with a union (spoiler alert: it's much better):

public record LoggedIn(string UserName); public record InvalidCredentials(int AttemptsLeft); public record AccountLocked(DateTimeOffset Until); public union LoginResult(LoggedIn, InvalidCredentials, AccountLocked); // AuthService stays exactly the same, line for line. 

AuthService doesn't change at all. Each case type converts to LoginResult implicitly, so return new InvalidCredentials(...) just works.

The calling code loses its discard arm:

var authService = new AuthService(); while (true) { Console.Write("User name: "); string? userName = Console.ReadLine(); Console.Write("Password: "); string? password = Console.ReadLine(); if (userName is null || password is null) break; // the input stream was closed (Ctrl+Z on Windows, Ctrl+D on macOS/Linux) LoginResult result = authService.Login(userName, password); string message = result switch { LoggedIn l => $"Welcome back, {l.UserName}!", InvalidCredentials c => $"Wrong user name or password. {c.AttemptsLeft} attempts left.", AccountLocked a => $"Too many attempts. Try again after {a.Until:t}." }; Console.WriteLine(message); Console.WriteLine(); } 

The compiler knows the list is complete, so the switch is exhaustive without _.

Now let's add two-factor authentication:

public record TwoFactorRequired(string Method); public union LoginResult(LoggedIn, InvalidCredentials, AccountLocked, TwoFactorRequired); // Plus the same _twoFactorUsers field and check in AuthService as before. 

This time, every switch over LoginResult that doesn't handle TwoFactorRequired gets a compiler warning. You see every place you need to update before the code ships, not after the app crashes for the first two-factor user.

Error

Add the missing arm, and Linus gets asked for his code instead of crashing the app:

TwoFactorRequired t => $"Password accepted. Enter the code from your {t.Method}.", 

Error Gone

If you want that warning to fail the build, add this to your project file:

<WarningsAsErrors>CS8509</WarningsAsErrors> 

CS8509 is the "switch expression does not handle all possible values" warning. Turning it into an error is a cheap way to make sure nobody ignores it.

csproj file

Error1

How C# Unions Actually Work

The syntax is small, but there are a few rules worth knowing.

Declaring a Union

A union is the union keyword, a name, and a list of case types in parentheses:

public union Pet(Cat, Dog, Bird); public union IntOrString(int, string); public union Option<T>(None, Some<T>); 

Case types can be almost anything: classes, records, structs, interfaces, generic type parameters, nullable types, and even other unions. They don't need a common base type.

A union can also have a body with helper members:

public record Meters(double Value); public record Feet(double Value); public union Length(Meters, Feet) { public double TotalMeters => this switch { Meters m => m.Value, Feet f => f.Value * 0.3048, _ => throw new InvalidOperationException("The Length has no value."), }; } 

The body can't add instance fields or auto-properties. A union holds one value, and that's it.

Pattern Matching Unwraps for You

When you write pet is Dog d or a Dog d => arm in a switch, the compiler checks the value inside the union, not the union itself. You never have to write pet.Value is Dog d, although you can.

Two patterns are the exception: var and _ match the union itself, without unwrapping it. That matters more than it looks.

Do We Actually Need Them?

Fair question. C# has survived 25 years without unions, and we've shipped plenty of working software. So let's be honest about both sides.

The Case for Unions

  • The compiler checks your work. This is the big one. Exhaustive matching turns "I hope I updated every switch" into a list of warnings. On a large codebase with several teams, that's worth a lot.
  • Signatures tell the truth. Task<User> hides the fact that the user might not exist, or that the caller might not be allowed to see it. Task<GetUserResult> with union GetUserResult(User, NotFound, Forbidden) says it out loud.
  • Fewer exceptions for expected outcomes. "Wrong password" isn't exceptional. It happens every day. Unions let you return it as a value instead of throwing and catching.
  • No inheritance tax. Case types don't need a shared base class, so you can combine types you don't own, like string, int or Exception.
  • One less dependency. Libraries like OneOf did a great job filling the gap. Now the language does it natively.

The Case Against (Or at Least, for Caution)

  • Another way to do the same thing. C# now has abstract classes, interfaces, closed hierarchies, and unions for modeling "one of these." Teams will need conventions about which to use where.
  • Boxing. Value-type cases are boxed in the generated struct. That's fine for most code, but it matters in performance-critical paths.
  • The default hole. A union struct can be default, which means empty. Exhaustive doesn't mean bulletproof.
  • Overuse. Not every method needs a union return type. If a method can only fail because of a bug, an exception is still the right tool.

My Take

Unions are not a revolution, and they won't replace classes or interfaces. They're a precise tool for one specific job: modeling a value that can be one of a known, fixed set of things.

That job comes up constantly in real code, in API results, workflow states, messages and parsers. Until now, we did it with workarounds the compiler couldn't verify.

So yes, I think they're needed. Not because we couldn't write the code before, but because now the compiler can tell us when that code is wrong.

Wrapping Up

Unions don't let C# do anything it couldn't do before. What they change is who catches the mistakes. With base classes and discard arms, finding the missing case was your job, or your customer's. With unions, it's the compiler's job.

In the next article, we'll open up the compiled DLL and see what a union really looks like under the hood. So stay tuned!

Let's stay connected!