All the code in this series is available on GitHub. Clone it, run it, and try breaking it yourself.
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
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
- Unions Aren't Magic
- What You'll Need
- Opening the DLL
- Decompiling with ILSpy
- The First Surprise
- Breaking Down the Struct
[Union]: A Label for the Compilerstruct: A Value TypeIUnionandValue: One Slot for Every Case- One Constructor per Case
- Where the Conversions Happen
- What a Switch on a Union Becomes
- Wrapping Up
Unions Aren't Magic
Unions are great. You declare a type in one line and the compiler checks every switch expression for you, and the "impossible" branch finally stays impossible. Joy of joys!
But unions aren't magic. There's no new runtime type, no special instruction in the CLR, and no hidden framework doing the work at runtime. Everything happens at compile time. The compiler takes your one-line union declaration and turns it into ordinary C# that .NET has understood for years.
So what does that ordinary code look like?
In the previous article of this series, we looked at what unions are, how to use them, and whether we actually need them. This time, we're going to pop the hood. We'll take the project from the previous article, open its compiled DLL, and look at what the compiler really generates when you write union.
Major spoiler alert: it's a struct.
What You'll Need
You don't need much to follow along:
- .NET 11 SDK. Run
dotnet --list-sdksand check that you see11.0.x. - VS Code with the C# Dev Kit extension, or any other .NET IDE.
- A way to see IL. In VS Code, install the ILSpy .NET Decompiler extension (
icsharpcode.ilspy-vscode). ILSpy also runs as a standalone app.
If you use JetBrains Rider, you don't need anything extra: it has a built-in IL Viewer that shows the IL for the code under your cursor, and it can also decompile assemblies.
- The project from the previous article. Clone the repository and build it in Release mode:
git clone https://github.com/georgekobaidze/dotnet11-playground.git cd dotnet11-playground dotnet build -c Release Why Release? Debug builds add extra instructions and variables to make debugging easier. Release shows you what actually ships.
After the build, the compiled DLL is at src/Unions/bin/Release/net11.0/Unions.dll. That's the file we're going to open.
Opening the DLL
Let's start with the union from the previous article. Here's its source code, from src/Unions/LoginService/LoginAfter.cs:
public record LoggedIn(string UserName); public record InvalidCredentials(int AttemptsLeft); public record AccountLocked(DateTimeOffset Until); public record TwoFactorRequired(string Method); public union LoginResult(LoggedIn, InvalidCredentials, AccountLocked, TwoFactorRequired); Four records and one line that groups them. Now let's see what that line turned into.
Decompiling with ILSpy
- Open the command palette (
Ctrl+Shift+P, orCmd+Shift+Pon macOS) and typeILSpy. - Choose the command that opens an assembly, and pick
src/Unions/bin/Release/net11.0/Unions.dll. - A new ILSpy: Assemblies view appears in the Explorer. Expand
Unions, then theUnions.Afternamespace, and findLoginResult. - Click it. ILSpy decompiles it and shows the result in an editor tab.
By default, ILSpy shows decompiled C#. To see the raw IL, click the Output: C# … item in VS Code's status bar (bottom right) and pick IL. We'll use both: C# to understand the shape of the type, and IL to see exactly what the compiler emitted.
The First Surprise
The project has two types called LoginResult, one from each version of the login code:
-
Unions.Before.LoginResultis the abstract record we used before C# 15. -
Unions.After.LoginResultis the union.
First let's look at the decompiled C# code of the old LoginResult:
It's an abstract record, just like in the source code.
Now let's look at the new LoginResult.
As you can see here, it's a struct behind the mask. Unions, you've been exposed.
That's the main idea of this article: there's no "union" in the compiled code. The runtime has never heard of unions. There's only an ordinary struct that the compiler wrote for you.
And now let's look at the IL code.
A quick warning about the IL view: don't try to read it line by line. IL is a low-level, stack-based instruction set written for the runtime, not for humans. Skim it for the parts we care about (the type declaration, its attributes, and the method signatures) and leave the rest to the JIT compiler.
Now let's break this struct down piece by piece and see what each part does.
Breaking Down the Struct
Let's go through the generated LoginResult from top to bottom.
[Union]: A Label for the Compiler
[Union] public struct LoginResult : IUnion The first thing on the type is the [Union] attribute. It comes from System.Runtime.CompilerServices, which is why ILSpy added that using at the top of the file.
The attribute doesn't do anything at runtime. It's a label for the compiler. When another project references Unions.dll and uses LoginResult, the compiler reads this attribute and knows to treat the struct as a union: it allows the implicit conversions and checks your switch expressions for exhaustiveness.
It also means the union keyword isn't the only way to get a union. Any struct or class with the [Union] attribute and the right shape (single-parameter constructors and a Value property) gets the same treatment. Union libraries can use this to plug into the compiler's checks without users switching to the new syntax.
struct: A Value Type
The compiler chose a struct, not a class. That means a LoginResult variable holds the union directly, not a reference to it, and creating one doesn't allocate a separate wrapper object on the heap. The wrapper is just one field, as we'll see in a moment.
IUnion and Value: One Slot for Every Case
public object? Value { get; } This is the heart of the union. There's one property, and it holds whichever case is current. Look at the assembly tree: there's only one field, <Value>k__BackingField, the compiler-generated storage behind this auto-property. That's why a union can never hold two cases at once: there's simply nowhere to put the second one.
Notice the type: object?. At runtime, the struct doesn't know or care that Value can only be a LoggedIn, InvalidCredentials, AccountLocked or TwoFactorRequired. That rule exists only at compile time. The compiler enforces it, and the generated code just stores an object.
The property is also get-only, so a union can't change after it's created. The IL backs this up: the backing field is marked initonly (IL's version of readonly), and the getter carries an IsReadOnly attribute. When you assign a new case to a variable, you replace the whole struct.
The IUnion interface is the contract behind this property. Any union, whether declared with union or hand-written with [Union], exposes its current case through Value.
One Constructor per Case
[CompilerGenerated] public LoginResult(LoggedIn value) { Value = value; } The compiler generated one constructor for each case type: LoggedIn, InvalidCredentials, AccountLocked, and TwoFactorRequired. Each one does exactly one thing: it stores the value in Value. The [CompilerGenerated] attribute marks them as code you didn't write yourself.
These constructors are where the implicit conversions come from. We'll see them in action in a moment.
It also explains why only the listed types are accepted. There's no LoginResult(string) constructor, so there's no conversion from string.
Where the Conversions Happen
Remember this line from AuthService.Login?
return new InvalidCredentials(MaxAttempts - failed); The method returns a LoginResult, but we return an InvalidCredentials. Open Unions.After → AuthService → Login(string, string) in ILSpy to see how that works:
There's no magic conversion. The compiler simply wrapped the record in one of the constructors we saw earlier, the one that takes an InvalidCredentials. That's why we didn't have to change a single line of AuthService in the previous article. (And if you're wondering where MaxAttempts went: it's a const, so the compiler replaced it with its value, 3.) In the IL view, you'll see it as a newobj instruction calling LoginResult::.ctor.
What a Switch on a Union Becomes
Now for the part that makes unions worth using: the exhaustive switch. Our top-level code in Program.cs compiles into a hidden Program class with a <Main>$ method. You'll find it under the empty namespace node ({ }) in the assembly tree.
The compiler copies loginResult.Value into a local variable, and the switch expression becomes a series of type checks on Value: is it a LoggedIn? An InvalidCredentials? An AccountLocked? A TwoFactorRequired?
Look closely: our exhaustive switch expression turned into a chain of nested if/else checks. That's the exact form that doesn't get exhaustiveness checking when you write it yourself. The safety comes from what you write, not from what runs.
So where's the exhaustiveness? It's not in the output. It was checked at compile time and then thrown away. The runtime never sees it, which is why the compiler still adds one last branch: if none of the type checks match, it calls a compiler-generated helper that throws a SwitchExpressionException. That branch runs only in one situation: an empty, default union whose Value is null.
The compiler checks your work. The runtime just runs plain type checks.
Wrapping Up
We popped the hood, and here's what we found: unions aren't magic. They're a compiler feature, not a runtime feature.
When you write one line:
public union LoginResult(LoggedIn, InvalidCredentials, AccountLocked, TwoFactorRequired); the compiler turns it into an ordinary struct:
- a
[Union]attribute and theIUnioninterface, so the compiler recognizes it as a union, - a single
object? Valueproperty that holds the current case, - and one constructor per case type, which is where the implicit conversions come from.
Your switch expressions become plain type checks on Value. The exhaustiveness check, the feature that makes unions worth using, happens entirely at compile time. By the time your code runs, it's gone.
Knowing this explains a few things that might otherwise feel strange:
- Why
defaultis empty. It's a struct, and every struct has a default value. - Why value-type cases get boxed. Everything is stored in an
object?. - Why switch expressions matter. The compiler can only check what it sees at compile time. Write the same logic as an
if/elsechain or a classicswitchstatement, and that check is gone.
None of this makes unions less useful. It makes them predictable. You now know exactly what you're shipping.
I have to admit: in the AI era, there's something incredibly satisfying about digging through low-level IL code yourself.
If you haven't read it yet, start with the first article to see unions in action. All the code from both articles is in the GitHub repository. Clone it, open Unions.dll in ILSpy or Rider, and pop the hood yourself.
What surprised you most about what the compiler generates? Let me know in the comments.
Let's stay connected!









