The closed modifier in C# 15 and .NET 11 tells the compiler that a class's direct subclasses are complete and live in its own assembly. That makes switch expressions over the hierarchy exhaustive, so no discard arm or UnreachableException is needed.
Key points
- closed is on by default for projects targeting net11.0, so no opt-in switch is required.
- A closed class is implicitly abstract and can only be derived from inside its own assembly; otherwise CS9382.
- Covering every direct subclass makes a switch expression exhaustive, and a missing case raises CS8509.
- Adding a new subclass later flags each switch that does not handle it, at compile time.
- The rule is not transitive: another assembly can still derive from a subclass that is neither sealed nor closed.
- Combining closed with sealed or static gives CS9381; an explicit abstract modifier gives CS9384.
Real-world use
- A build result modeled as succeeded, failed or canceled, matched in one exhaustive switch
- A Shape hierarchy that keeps Area virtual while a switch emits SVG for each shape
- A generic Result<T> built from Ok<T> and Error<T> in three lines
This summary was generated by the agent from the original post on NDepend Blog. The full text and all rights belong to its author and publisher. Go to original