What does the sealed keyword do in C#?

C# OOP Basic Fresher1–2 Yrs2–3 Yrs Conceptual 1 min read

Quick Answer

sealed on a class prevents any other class from inheriting it. sealed on an override method stops further derived classes from overriding that method (while still allowing them to inherit the class). It communicates intent, prevents misuse of a class not designed for extension, and can let the JIT devirtualise calls.

sealed on a class means nothing can inherit from it — like string. On an override method it means subclasses further down can't override that particular method any more. I use it to say “this type isn't designed to be extended” — value objects, helpers — which prevents people subclassing something that would break if they did. There's also a small performance angle: the JIT knows a sealed type can't have subclasses so it can sometimes devirtualise the call.

  • Sealed class — public sealed class Money { }. Useful for value objects, utility classes, and anything whose behaviour shouldn't be changed by subclassing. string is sealed.
  • Sealed override — public sealed override void Save() { } in a middle class of a hierarchy.
  • Performance — the JIT knows a sealed type has no subclasses, so a virtual call on a sealed type (or through a sealed reference) can sometimes be devirtualised or inlined. Minor, but real in hot paths.
  • Design — “design for inheritance or prohibit it.” Sealing by default and opening up deliberately is a reasonable stance.