Closed classes in C# 15 and what they don't close
A test across two assemblies shows error CS9382, how a grandchild class slips past the rule and where System.Text.Json inference stops.
C# 15 shipped with .NET 11 on November 10. I already wrote about union types. The same release has a second feature for a similar problem: closed hierarchies. You add the closed modifier to a base class, and only code in the same assembly can derive directly from it.
The docs explain the basic rules well. I wanted to see what happens at the edges, so I built a few small projects. A class library holds a meetup agenda, a second library tries to extend it, and a console app uses both.
A meetup agenda as a closed hierarchy
A meetup has a few kinds of sessions. All of them have a title, and each kind has its own data:
1
2
3
4
5
6
7
namespace Meetup.Core;
public closed record Session(string Title);
public record Talk(string Title, string Speaker) : Session(Title);
public sealed record Panel(string Title, string[] Panelists) : Session(Title);
public sealed record Workshop(string Title, int Seats) : Session(Title);
closed works on classes and record classes. A closed class is implicitly abstract, so new Session("Pizza") fails with CS0144. The compiler also rejects a few combinations:
closed sealedorclosed staticgives CS9381closed abstractgives CS9384 because the class is already abstractclosed structandclosed interfacegive CS0106
Talk is not sealed on purpose.
A switch that names the missing case
The compiler knows every direct descendant of Session, so this switch needs no discard arm and gives no warning:
1
2
3
4
5
6
static string Describe(Session session) => session switch
{
Talk t => $"{t.Title} by {t.Speaker}",
Panel p => $"{p.Title} with {p.Panelists.Length} panelists",
Workshop w => $"{w.Title}, {w.Seats} seats",
};
With a plain abstract base class, the same switch gets CS8509. Now let’s add a fourth type to the library:
1
public sealed record Hackathon(string Title, int Teams) : Session(Title);
After you rebuild the library and the app, every switch expression over Session that no longer covers all cases gets a warning that names the missing type. A switch with a discard arm (_) already handles Hackathon, so it stays silent:
1
2
warning CS8509: The switch expression does not handle all possible values of its input type
(it is not exhaustive). For example, the pattern 'Meetup.Core.Hackathon' is not covered.
For an open hierarchy, the same warning only says that the pattern '_' is not covered. With a closed one, you see exactly what to add. As with unions, I would make CS8509 an error in projects that use this feature. A new session type should break the build, not wait for someone to read the warnings.
A few more details:
- When the input is
Session?, you also need anullarm. Without it, you get CS8655. - If a
nullstill gets into a non-nullableSession, for example from code with nullable warnings turned off, the switch throwsSwitchExpressionExceptionat runtime. switchstatements don’t get this check. They compile without a warning afterHackathonis added.
What happens when another assembly tries to derive?
It doesn’t compile. The second library, Meetup.Plugin, references Meetup.Core and tries this:
1
2
3
4
5
using Meetup.Core;
namespace Meetup.Plugin;
public record CodingDojo(string Title, int Pairs) : Session(Title);
1
error CS9382: 'CodingDojo': cannot use a closed type 'Session' from another assembly as a base type.
The docs show this case without the error code, so it helps to know CS9382 when it shows up in a build log.
The rule is also stored in metadata. The compiler marks Session with IsClosedTypeAttribute and adds [CompilerFeatureRequired("ClosedClasses")] to every constructor. Reflection on the built assembly shows both. A compiler that knows this attribute but not the feature refuses to call those constructors. The spec uses Visual Basic as the example.
A consuming project with <LangVersion>14</LangVersion> keeps one rule and loses the other. Deriving from Session still fails with CS9382. The Describe switch, however, gets CS8509 with '_' again. The derivation rule applies at any language version, but the exhaustiveness check needs C# 15 in the consuming project, so a project that pins C# 14 still needs the discard arm.
A closed class doesn’t close its children
The closed rule covers only direct descendants. Talk is not sealed, so the plugin can extend it:
1
public record LightningTalk(string Title, string Speaker) : Talk(Title, Speaker);
This compiles. The Describe switch stays exhaustive because the Talk arm also matches every LightningTalk. Nothing warns the app that a new kind of talk exists, and it is shown as a regular talk.
A library author can’t stop others from adding new kinds of talks unless Talk is sealed or closed. My default would be to seal every leaf type in a closed hierarchy and leave a type open only when other assemblies really need to extend it.
Does System.Text.Json see the whole hierarchy?
Only the first level. .NET 11 adds InferClosedTypePolymorphism to System.Text.Json. With it, you don’t need a [JsonDerivedType] attribute for every descendant:
1
2
[JsonPolymorphic(InferClosedTypePolymorphism = true)]
public closed record Session(string Title);
A talk serialized as Session gets its simple type name as the discriminator:
1
{"$type":"Talk","Speaker":"Ola","Title":"Closed classes in C# 15"}
JsonSerializer.Deserialize<Session> turns this JSON back into a Talk.
A keynote is a special kind of talk, so it derives from Talk in the same assembly:
1
public sealed record Keynote(string Title, string Speaker) : Talk(Title, Speaker);
Serializing a Keynote as Session throws:
1
2
NotSupportedException: Runtime type 'Meetup.Core.Keynote' is not supported
by polymorphic type 'Meetup.Core.Session'. Path: $.
The LightningTalk from the plugin fails with the same exception. The docs say the serializer registers each derived type. In practice that means each direct one, which is the same set the compiler uses for exhaustiveness.
You can set UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor. With that setting, both types are written with "$type":"Talk" and come back as a plain Talk, so the real type is lost.
The discriminator is the type name, which means that renaming a class changes your JSON. Two classes with the same name in different namespaces collide too. For internal messages I can live with that.
For a public API contract, I would still register the types with [JsonDerivedType] and fixed discriminator names. Even one [JsonDerivedType] turns inference off for that hierarchy, so then you list every type yourself.
Closed class or union?
Both features give you an exhaustive switch. They model different things:
- A closed class is a normal inheritance hierarchy. The cases share data and behaviour from the base class, like
Titlehere, and you write all direct cases in one assembly. It is a reference type, and System.Text.Json can write a$typediscriminator for it. - A union groups types that already exist and may share nothing, for example
intandstring, or two records from different libraries. The case types don’t need to know about the union, and one type can be a case in many unions. A generated union is a struct and boxes value types. A union is written as the bare case value, with no discriminator.
My rule of thumb: if you own all the cases and they have something in common, use a closed class. If you combine types that already exist, use a union. I wrote more about unions in Union types are in C# 15. What do you actually get?
Everything here needs the .NET 11 SDK and a net11.0 project, where C# 15 is the default.
Sources:
- What’s new in C# 15 - Microsoft Learn
- closed modifier - C# language reference
- Closed hierarchy patterns - C# language reference
- Closed hierarchies - C# feature specification
- Infer polymorphism from a closed hierarchy - System.Text.Json docs
- Serialize union types with System.Text.Json - System.Text.Json docs
- Announcing .NET 11 - .NET Blog
Cover image generated with gpt-image-2.5-sunburst from my photo.
