sealed and sealed hierarchies
sealed class
sealed on a class means no class may derive from it. The compiler enforces the rule with a real diagnostic, which is the fastest way to see what the keyword protects:
var cat = new Cat("Mochi");
Console.WriteLine(cat.Name);
sealed class Cat
{
public Cat(string name) => Name = name;
public string Name { get; }
}
class Kitten : Cat
{
public Kitten()
: base("small")
{
}
}
dotnet build
Program.cs(11,16): error CS0509: 'Kitten': cannot derive from sealed type 'Cat'
Build FAILED.
Program.cs(11,16): error CS0509: 'Kitten': cannot derive from sealed type 'Cat'
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:05.23
The error points at the base list of the subclass, and both names are in the message. Sealing a class also tells the runtime that no override of its virtual methods can exist, which lets the JIT devirtualise a call to one: it is a small performance decision as well as a design one.
sealed override
On a method, sealed override takes a virtual method that a subclass overrides and closes it for everything below. This is how a middle layer says "this behaviour is final from here on":
var leaf = new Leaf();
Console.WriteLine(leaf.Describe());
class Base
{
public virtual string Describe() => "base";
}
class Middle : Base
{
public sealed override string Describe() => "middle";
}
class Leaf : Middle
{
public override string Describe() => "leaf";
}
dotnet build
Program.cs(16,28): error CS0239: 'Leaf.Describe()': cannot override inherited member 'Middle.Describe()' because it is sealed
Build FAILED.
Program.cs(16,28): error CS0239: 'Leaf.Describe()': cannot override inherited member 'Middle.Describe()' because it is sealed
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:05.16
The message names the member that closed the slot, which is the useful part: a reader who expected to override it learns where the chain was stopped. Without the override keyword, sealed has nothing to seal and the compiler says so with error CS0238.
A closed set of types
A private constructor plus a static factory plus private sealed subclasses gives a type whose complete set of cases is known inside one file. The pattern is worth learning because it is how a result type, a message or a small state machine is written when a class hierarchy is wanted:
var results = new[] { Result.Ok(42), Result.Error("bad input") };
foreach (var result in results)
{
Console.WriteLine(result.Describe());
}
Console.WriteLine($"count: {results.Length}");
abstract class Result
{
private Result()
{
}
public static Result Ok(int value) => new OkResult(value);
public static Result Error(string message) => new ErrorResult(message);
public abstract string Describe();
private sealed class OkResult(int value) : Result
{
public override string Describe() => $"ok {value}";
}
private sealed class ErrorResult(string message) : Result
{
public override string Describe() => $"error {message}";
}
}
dotnet run
ok 42
error bad input
count: 2
No code outside the class can derive from Result, because Result has no accessible constructor, so the two nested classes are the whole set of cases. The two factories are the only way to get a value, and each returns the base type. A switch over the result can then be exhaustive in the reader head even though the compiler cannot check it, which is the trade against a record hierarchy.
Why seal a type
- A design that is complete: a value type, a result, a message. A subclass would have to guess what the author meant.
- Performance in a hot path: a sealed class or a sealed override can be devirtualised, so a virtual call costs what a direct call costs.
- Security and invariants: a class that protects a resource cannot be replaced by a subclass that skips the check.
- Not by default. A library type that may be extended by its users should stay open, and sealing it later is a breaking change; the .NET guidelines discuss both sides.
Exercises
- Remove sealed from Cat and run the first program. What does the kitten print?
- Add a Result.Pending() factory and a third private sealed class for it.
- Write a record hierarchy that does the same as Result with record and is checks, and compare the two shapes.
- Try sealed on a method that is not an override and read the error.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does sealing a class prevent?
Answer
Any class deriving from it
CS0509 reports the attempt to derive from a sealed type.
-
What can
sealed overrideclose?Answer
A virtual method, for every class below
It overrides a virtual slot and stops further overriding of that member.
-
What does this program print?
B b = new M(); Console.WriteLine(b.Who()); class B { public virtual string Who() => "b"; } class M : B { public sealed override string Who() => "m"; }Answer
m
The override is still an override; sealing only stops classes below M.
-
What makes the Result hierarchy closed?
Answer
A private constructor and private sealed subclasses
Nothing outside can derive from a type whose only constructor is private.
-
What does CS0239 report?
Answer
An override of a member that is sealed
The error names the sealed member that cannot be overridden again.
-
What does this program print?
var r = Result.Ok(1); Console.WriteLine(r.Describe()); abstract class Result { private Result() { } public static Result Ok(int v) => new OkResult(v); public abstract string Describe(); private sealed class OkResult(int v) : Result { public override string Describe() => $"ok {v}"; } }Answer
ok 1
The nested class can call the private base constructor, and the factory returns it as Result.
-
Why can sealing a class make a virtual call faster?
Answer
The JIT knows no override can exist and can call directly
Devirtualisation is possible when the runtime type is known to have no further overrides.
-
What does
sealedon a method withoutoverridemean?Answer
It is an error, CS0238
sealed needs a virtual slot to close, which only an override has.
-
Which type in the BCL is sealed?
Answer
String
String is sealed; Exception and Stream are designed for derivation.
-
When is sealing a public library class a bad idea?
Answer
When its users are expected to extend it, and sealing later breaks them
Sealing is a one-way compatibility decision: unsealing is safe, sealing is not.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev