C# in .NET 11 preview 5 introduces the `closed` keyword for class hierarchies, restricting derivation to a single assembly. Unlike the private constructor workaround, `closed` gives the compiler full knowledge of all derived types, enabling exhaustiveness checking in switch expressions. When all derived types are also `sealed`, the compiler can catch guaranteed runtime cast failures at compile time. The post covers how to enable the feature (setting `<LangVersion>preview</LangVersion>` and manually defining the `[Closed]` attribute), its limitations (implicit abstract, generic constraints), and how it compares to the new union types feature also coming in .NET 11.
Table of contents
What is a "closed class hierarchy"?Couldn't we do this already with private constructors?Exhaustiveness checking in switch expressionsHow do closed class hierarchies relate to unions?Using closed class hierarchies in .NET 11What are the limitations and features of closed class hierarchies?Making a closed hierarchy a sealed hierarchyHow are closed hierarchies implemented?Summary14.5K Impressions