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

Exercises

  1. Remove sealed from Cat and run the first program. What does the kitten print?
  2. Add a Result.Pending() factory and a third private sealed class for it.
  3. Write a record hierarchy that does the same as Result with record and is checks, and compare the two shapes.
  4. 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.

  1. What does sealing a class prevent?

    Answer

    Any class deriving from it

    CS0509 reports the attempt to derive from a sealed type.

  2. What can sealed override close?

    Answer

    A virtual method, for every class below

    It overrides a virtual slot and stops further overriding of that member.

  3. 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.

  4. 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.

  5. What does CS0239 report?

    Answer

    An override of a member that is sealed

    The error names the sealed member that cannot be overridden again.

  6. 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.

  7. 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.

  8. What does sealed on a method without override mean?

    Answer

    It is an error, CS0238

    sealed needs a virtual slot to close, which only an override has.

  9. Which type in the BCL is sealed?

    Answer

    String

    String is sealed; Exception and Stream are designed for derivation.

  10. 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