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 | Console examples: the login flow (before and after unions), plus samples for parsing input, a state machine, user commands, and combining types you don't own. |
| UnionsWebApi | Union types | A minimal API that returns a union from a service and maps each outcome to an HTTP response. |
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… Follow me on GitHub for more updates!
Table of Contents
- Where We Left Off
- The Default Arm Nobody Believes In
- Closing the Hierarchy
- The Rules of Closed
- Closed vs Internal
- Closed Hierarchies vs Unions
- Wrapping Up
Where We Left Off
A few articles ago, we went deep on union types: what they are, what they compile to, and where they shine in real code. A union lets you tell the compiler, "this value is exactly one of these types, and nothing else." In return, the compiler checks that your switch handles every case.
After a quick retro detour through labeled loops, it's time to get back to that idea, because unions aren't the only way to model "one of a fixed set of things" in C#. For decades, we've used something else for that: a good old class hierarchy.
And class hierarchies have always had one annoying problem.
The Default Arm Nobody Believes In
Let's say we're modeling the status of an order:
public abstract record OrderStatus; public record Pending : OrderStatus; public record Shipped(string TrackingNumber) : OrderStatus; public record Delivered(DateTime DeliveredAt) : OrderStatus; Three statuses, and we handle all three:
string Describe(OrderStatus status) => status switch { Pending => "Waiting to be shipped", Shipped s => $"On the way: {s.TrackingNumber}", Delivered d => $"Delivered on {d.DeliveredAt:d}", }; Every case is covered. But the compiler still isn't happy: it warns that the switch expression isn't exhaustive (CS8509).
From the compiler's point of view, it's right. OrderStatus is an ordinary abstract record, so anyone, anywhere, can create a new subclass. Another project could add Returned tomorrow, and our switch would have no idea. The number of subclasses is unbounded, and the compiler has no way of knowing them all.
So we do what we've always done and add an arm we don't believe in:
_ => throw new UnreachableException() "Unreachable." Until someone adds Returned, and then it isn't. Instead of a compile-time warning telling you to handle the new case, you get a runtime exception in production.
We know the list of statuses is complete. We just had no way to tell the compiler.
Closing the Hierarchy
Here's our order status again, with one new word:
public closed record OrderStatus; public record Pending : OrderStatus; public record Shipped(string TrackingNumber) : OrderStatus; public record Delivered(DateTime DeliveredAt) : OrderStatus; And here's our switch, without the arm nobody believed in:
string Describe(OrderStatus status) => status switch { Pending => "Waiting to be shipped", Shipped s => $"On the way: {s.TrackingNumber}", Delivered d => $"Delivered on {d.DeliveredAt:d}", }; No warning. No UnreachableException. The compiler knows Pending, Shipped, and Delivered are the only direct subclasses of OrderStatus, so it knows the switch covers everything.
But the real payoff comes later. Let's say a teammate adds a new status:
public record Returned(string Reason) : OrderStatus; Before C# 15, our switch would compile just fine, and the new status would fall straight into _ => throw new UnreachableException() at runtime. Now, the compiler immediately warns that the switch isn't exhaustive anymore and points us to every place that needs to handle Returned.
The bug moves from production to your IDE. That's the whole point.
The Rules of Closed
closed is simple, but it comes with a few rules.
Rule #1: A closed class is implicitly abstract
You can't create an instance of OrderStatus itself, only its subclasses. That makes sense: if you could create a plain OrderStatus, it would be a fourth case the switch doesn't handle.
Because of that, you can't combine closed with abstract (it's already abstract), sealed (closed classes exist to be derived from), or static.
Rule #2: Subclasses must live in the same assembly
That's the whole point. Only code in the same assembly can derive from a closed class. That's what makes the list of subclasses complete: no other project can sneak a new one in.
The class itself can still be public. Everyone can see it, use it, and pattern-match on it. They just can't extend it.
Rule #3: It's not transitive
closed only applies to the direct subclasses. If Shipped isn't closed itself, another assembly can still derive from it:
// In another assembly public record ShippedExpress(string TrackingNumber, string Carrier) : Shipped(TrackingNumber); Does that break our switch? No. ShippedExpress is a Shipped, so the Shipped s arm still matches it. The switch stays exhaustive.
But if you want exhaustive checking one level deeper (say, a switch over all the kinds of Shipped), you have to mark Shipped as closed too. Keep Rule #1 in mind, though: that also makes Shipped abstract, so you can no longer create a plain Shipped.
Closed vs Internal
At first glance, closed might sound like internal. Both keep other assemblies out. But they control very different things:
internalcontrols who can see and use a type.closedcontrols who can inherit from a type.
internal | closed | |
|---|---|---|
| What it controls | Visibility | Inheritance |
| Can other assemblies use the type? | No | Yes, if it's public |
| Can other assemblies inherit from it? | No | No |
Exhaustive switch without a default arm? | No | Yes |
Implicitly abstract? | No | Yes |
The exhaustiveness row is the big one. Even an internal hierarchy isn't treated as complete by the compiler, so it still needs a default arm.
The old trick
Before C# 15, if you wanted a hierarchy that other assemblies could use but not extend, you'd use a trick like this:
public abstract class OrderStatus { internal OrderStatus() { } // only this assembly can call it } Other assemblies can see OrderStatus, but they can't call its constructor, so they can't subclass it.
It works, but only as a convention. The compiler doesn't understand your intent, so you still need the default arm in every switch. And InternalsVisibleTo can let other assemblies in anyway. closed turns that convention into something the compiler understands and enforces.
Closed Hierarchies vs Unions
So now C# has two ways to say "one of a fixed set of things." Which one should you use?
| Union | Closed hierarchy | |
|---|---|---|
| Cases need a common base type | No | Yes |
| Works with primitives and types you don't own | Yes | No |
| Shared members in a base type | No | Yes |
Exhaustive switch | Yes | Yes |
| Where the cases live | Anywhere | Same assembly |
The way I think about it:
- Use a union when the cases have nothing in common. An
intor astring. ACustomeror aCustomerNotFound. Types from a library you don't control. A union can combine them without forcing them into a family. - Use a closed hierarchy when the cases are a family. Order statuses, payment events, shapes: types you design together, that share a base and maybe some common members.
The JSON angle
If your types go over the wire, this matters even more.
A union serializes as just its active case, with no wrapper and no discriminator. That's great for matching an existing contract, but a client reading the JSON can't always tell which case it got.
A closed hierarchy can opt in to polymorphic serialization, and System.Text.Json works out the subclasses from the hierarchy on its own, without a [JsonDerivedType] for each one:
[JsonPolymorphic(InferClosedTypePolymorphism = true)] public closed record OrderStatus; Each object then carries a $type discriminator with the subclass name:
{"$type":"Shipped","trackingNumber":"TRK-12345"} Microsoft's own guidance follows the same logic: for a new API where you control all the cases, prefer a closed hierarchy with a discriminator. Use a union to preserve an existing discriminator-free contract, or when the cases can't share a base class.
Wrapping Up
Closed hierarchies fix a problem we've worked around for as long as C# has had inheritance: the compiler never knew when a hierarchy was complete.
Quick recap:
-
closedlimits inheritance to the declaring assembly, which tells the compiler the list of direct subclasses is complete. - That makes
switchexpressions exhaustive without a default arm. - Adding a new subclass becomes a compile-time warning instead of a runtime exception.
- A closed class is implicitly abstract, and
closedisn't transitive. -
closedis about inheritance,internalis about visibility. - Unions are for unrelated cases. Closed hierarchies are for families of types you design together.
All the code from this article is in my .NET 11 playground: dotnet11-playground.
Which one will you reach for first, unions or closed hierarchies? Let me know in the comments. 👇
Let's stay connected!




