C# 15 Introduces Closed Hierarchies for Enhanced Inheritance Control
AI-generated context summary requested by a Free News Reader user. Sourced via Gemini from publicly available information — no paywalled content was accessed.
You hit a paywall. Here’s the context on this topic based on publicly available information. We did not access any paywalled content. View original article.
C# 15 Introduces Closed Hierarchies for Enhanced Inheritance Control
- C# 15 introduces the `closed` modifier, allowing developers to define inheritance hierarchies where direct subtypes are restricted to the declaring assembly.
- This new feature, currently in preview for .NET 11, addresses a long-standing gap in the language's inheritance model by enabling more explicit control over type extension.
Full Summary — powered by AI
C# 15 is set to introduce “closed hierarchies” through a new `closed` modifier, a feature designed to offer more granular control over class inheritance. Previously, C# developers had two main options for inheritance: making a class `abstract` to allow unrestricted inheritance, or `sealed` to prevent any inheritance. The `closed` modifier provides a middle ground, enabling a class to be inherited, but only by types explicitly defined within the same assembly.
This addition aims to solve a problem that has existed since C#’s inception, where library authors couldn’t easily specify that a base type was intended for inheritance, but only by a predefined set of derived types. With `closed` hierarchies, the compiler can now guarantee exhaustiveness in `switch` expressions for these types because the complete set of direct descendants is known at compile time. This eliminates the need for a `default` arm in such `switch` statements, preventing potential runtime errors if new, unhandled derived types were introduced.
It’s important to note that the `closed` modifier implicitly makes a class `abstract` and cannot be combined with `sealed`, `static`, or an explicit `abstract` modifier. Additionally, the closure is not transitive; a class deriving from a `closed` class is not automatically `closed` itself. If the intention is to maintain exhaustiveness checking further down the inheritance tree, intermediate classes must also be explicitly marked as `closed`. This