C# 15 Closed Hierarchies: The closed Keyword Explained
The abstract keyword lets anyone add subclasses, and sealed lets nobody add them. C# 15's new closed keyword sits in between: only your own project can add subclasses, so the compiler finally knows the complete list.
Imagine a background job system. A job is always in one of four states: queued, running, completed or failed. You model each state as a small record that inherits from a base type called JobStatus, as you learned in the inheritance lessons.
Then you write a switch to show each state on screen, and the compiler insists on a _ => default arm. Why? Because as far as it knows, someone somewhere might create a fifth subclass tomorrow. You know that will never happen, but the compiler can't.
In this lesson, you'll learn how C# 15's closed modifier tells the compiler "these are all the subclasses there will ever be", how that makes switches complete without a default arm, and the few rules that keep it safe.
What Is It?
The Simple Explanation
Put the word closed in front of a class, and only code in the same project can create classes that inherit directly from it. Because the list of direct subclasses is now fixed, the compiler can check that a switch handles every one of them.
public closed record class JobStatus;
public record class Queued : JobStatus;
public record class Running(int PercentComplete) : JobStatus;
public record class Completed(TimeSpan Elapsed) : JobStatus;
public record class Failed(string Error) : JobStatus;The Technical Definition
Starting in C# 15, closed is a class modifier that declares a closed hierarchy. A direct subtype of a closed class must be declared in the same assembly (and module) as the closed class. A closed class is implicitly abstract and can't be combined with sealed, static or an explicit abstract. A switch expression whose arms handle every direct descendant of a closed class is exhaustive and needs no default arm. closed is a contextual keyword and applies only to classes, including record classes.
abstract (before)
- Any project can add new subclasses
- The compiler never knows the full list
- A switch over the subclasses needs _ =>
- New subclasses slip past your switches silently
closed (C# 15)
- Only the same project can add direct subclasses
- The compiler knows every direct subclass
- A switch that handles them all is complete
- Add a subclass and every incomplete switch gets a warning
Why Does It Exist?
The Problem — Inheritance Is Open by Default
In C#, any class that isn't sealed can be inherited from by any other code that can see it, including code in other projects. That openness is useful for frameworks, but it means the compiler can never be sure it has seen every subclass. So pattern-matching switches over a base type always needed a catch-all default arm, which hides mistakes when a new subclass is added.
The Solution — Close the List, Keep the Hierarchy
closed keeps everything good about inheritance: shared base members, records, constructors and methods. It also adds one promise: no surprise subclasses from outside your project. That single promise is enough for the compiler to check your switches for completeness.
Big Picture
How It Works
public closed record class JobStatus;- Queued, Running, Completed and Failed all inherit directly from JobStatus.
- A subclass in any other project is a compile error.
- It now knows JobStatus has exactly four direct subclasses, and also that JobStatus itself can never be created, because a closed class is implicitly abstract.
- If the arms cover all four subclasses, the switch is exhaustive: no _ => needed, and no warning.
- Add a fifth subclass later, and every switch that forgot it gets a warning.
Simple Example
JobStatus status = new Running(40);
Console.WriteLine(Describe(status)); // Running: 40% done
static string Describe(JobStatus status) => status switch
{
Queued => "Waiting to start",
Running r => $"Running: {r.PercentComplete}% done",
Completed c => $"Finished in {c.Elapsed.TotalSeconds:0.0} s",
Failed f => $"Failed: {f.Error}",
// No _ arm needed: these are all the direct subclasses of JobStatus.
};
public closed record class JobStatus;
public record class Queued : JobStatus;
public record class Running(int PercentComplete) : JobStatus;
public record class Completed(TimeSpan Elapsed) : JobStatus;
public record class Failed(string Error) : JobStatus;Code → Meaning → Result: status holds a Running record, so the second arm matches. Before C# 15, this exact switch produced a warning that it doesn't handle every possible input. With closed, the compiler knows these four records are the whole family.
Real-World Example
A closed hierarchy can share data through its base class, which a union can't do. Here every payment method carries an Amount, and each kind adds its own details:
PaymentMethod payment = new Card(100m, "4242");
Console.WriteLine(payment.Amount); // 100 (shared member from the base record)
Console.WriteLine(Fee(payment)); // 2.900
static decimal Fee(PaymentMethod payment) => payment switch
{
Card c => c.Amount * 0.029m, // 2.9% card fee
BankTransfer => 0.50m, // flat fee
Wallet w => w.Amount * 0.015m, // 1.5% wallet fee
};
public closed record class PaymentMethod(decimal Amount);
public record class Card(decimal Amount, string Last4) : PaymentMethod(Amount);
public record class BankTransfer(decimal Amount, string Iban) : PaymentMethod(Amount);
public record class Wallet(decimal Amount, string Provider) : PaymentMethod(Amount);Six months later the business adds gift cards. You add public record class GiftCard(decimal Amount, string Code) : PaymentMethod(Amount); and rebuild. The compiler immediately warns at Fee and at every other switch over PaymentMethod that doesn't handle GiftCard yet. With an ordinary abstract base and a _ => arm, nothing would have warned you, and gift cards would quietly have been charged the wrong fee.
Analogy
An abstract class is like a public family tree on a website: anyone, anywhere, can add a new child. A sealed class is a tree with no children allowed at all.
A closed class is a family tree that only the family itself can add children to, and only in the family home (your project). Anyone can read the tree, but nobody outside can add to it, so the family always knows exactly who all the children are.
Under the Hood
- Implicitly abstract. You can't write new JobStatus(), because a closed class is automatically abstract. That's also why closed abstract is an error: it would say the same thing twice.
- Only direct children are checked. The same-project rule applies to direct subclasses. A subclass of a subclass, such as something deriving from Failed, can live in another project unless Failed is itself sealed or closed.
- Visibility counts. A switch is only exhaustive where it can see every direct subclass. If a subclass is internal, code in another project can't see it, so a switch there still needs a default arm.
- A contextual keyword. closed only means something as a class modifier. You can still use closed as an ordinary variable name; where it would be ambiguous, write @closed.
Common Confusion
1. "closed is the same as sealed" — no, sealed allows no subclasses at all
sealed means nobody can inherit. closed means only this project can inherit directly. A closed class without any subclasses would be pointless, because you could never create anything of that type.
2. "closed protects the whole family tree" — no, only the first level
Closing JobStatus fixes its direct children. If another project should also be unable to extend Failed, mark Failed as sealed or closed too.
3. "I can close an interface or a struct" — no, classes only
closed works on classes, including record classes. Structs can't be inherited from anyway, and interfaces aren't covered. If you need a fixed set of unrelated types, that's what the union types from the previous lesson are for.
Common Mistakes
Mistake 1 — Declaring a subclass in a different project
The mistake: Putting public record class Paused : JobStatus; in a separate class library project and getting an error that JobStatus is a closed class.
The fix: Keep every direct subclass of a closed class in the same project as the base class. That restriction is exactly what makes the exhaustiveness check possible.
Mistake 2 — Keeping the old _ arm
The mistake: Upgrading a hierarchy to closed but leaving _ => "unknown" in every switch. The default arm still catches anything new, so the compiler can't warn you about a missing case.
The fix: Once the base class is closed and every subclass has its own arm, delete the default arm. Let the compiler do the checking.
Mistake 3 — Forgetting null for nullable variables
The mistake: Switching on a JobStatus? (a value that might be null) with arms for all four subclasses, and getting a warning that null isn't handled.
The fix: A nullable variable has one extra possibility: null. Add a null => "No status yet" arm.
When Should I Use It?
- States, results and events you design yourself, where the full list is part of your design: order states, job states, API responses, domain events.
- Library types that you switch over inside the library and don't want users to extend.
- When the cases share data or behaviour through a base class. If they don't share anything, a union is often simpler.
- Not for plug-in points, where other projects are supposed to add new subclasses. Leave those abstract.
Mental Model
A fixed list of children means the compiler can check that every switch is complete.
Only the first level is fixed; seal or close deeper levels if you need to.
Remember: closed = inheritance with a guest list, and the compiler can read the guest list.
Key Takeaway
- C# 15's closed modifier lets only the declaring project create direct subclasses of a class.
- A closed class is implicitly abstract and can't be combined with sealed, static or an explicit abstract.
- A switch that handles every direct subclass is exhaustive, with no default arm. Adding a subclass later produces warnings at every incomplete switch.
- Only direct children are restricted; mark deeper classes sealed or closed if needed.
- Use closed for hierarchies whose full list of cases is part of your design, and unions for unrelated types.
Check Your Understanding
Three questions on what closed promises and what it doesn't.
1. What does public closed record class JobStatus; allow?
Show answer
Correct: B
Why B is correct: closed restricts direct subclasses to the declaring assembly, which fixes the list of direct descendants at compile time.
Why A is incorrect: That describes sealed. A closed class is meant to have subclasses, just only from the same project.
Why C is incorrect: There's no "inherit once" rule. The restriction is about which project the subclass lives in.
Why D is incorrect: A closed class is implicitly abstract, so new JobStatus() is a compile error.
Reinforcement: closed = subclasses allowed, but only from home.
2. Why can a switch over a closed class skip the _ => arm?
Show answer
Correct: B
Why B is correct: With the list of direct subclasses fixed, the compiler can prove that the arms cover every possibility. That's the whole purpose of the feature.
Why A is incorrect: A variable of a closed type can still be null if it's declared nullable, and then you need a null arm.
Why C is incorrect: The runtime adds nothing. An unmatched value would throw a SwitchExpressionException, which the compiler's check prevents.
Why D is incorrect: Switches over ordinary open hierarchies still need a default arm to be exhaustive.
Reinforcement: Exhaustiveness comes from the compiler knowing the complete list.
3. Failed is a plain (not sealed, not closed) record that inherits from the closed JobStatus. Can a class in another project inherit from Failed?
Show answer
Correct: B
Why B is correct: Derivation from a closed class isn't transitive. Failed is an ordinary record, so other projects can extend it unless you mark it sealed or closed.
Why A is incorrect: The rule covers only direct descendants of the closed class. Deeper levels follow normal inheritance rules.
Why C is incorrect: abstract doesn't restrict who can inherit. Only sealed or closed would.
Why D is incorrect: The language version of the other project doesn't change this rule.
Reinforcement: closed fixes one level: close or seal deeper levels yourself.
Unions and closed hierarchies both help the compiler check your switches. The next lesson changes pace with a small, practical C# 15 addition: passing settings such as a capacity or a comparer straight into a collection expression.