C# Reference ยท Keywords and Statements
The sealed keyword
Reference for the C# sealed keyword: stop inheritance of a class, stop further overriding of a method, and understand the performance and design effects.
sealed closes a design to extension. Applied to a class, it means no other class can inherit from it. Applied to an overriding method, property, indexer or event, it means subclasses can no longer override that member, although the member remains an override of the base.
Sealing is a deliberate promise: the type's behavior will not be changed by subclasses. Many framework types are sealed (string, Uri, most attributes). Structs and enums are implicitly sealed, and a static class is both abstract and sealed in metadata.
sealed class Token { }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
sealed class Name { ... } sealed class Derived : Base { ... } public sealed override ReturnType Method(params) { ... } public sealed override Type Property { get; }
| Where | Effect |
|---|---|
| Class | Cannot be a base class. |
| Override member | Further overriding is blocked. |
sealed on a non-override member |
Not allowed (CS0238): a member must override something to be sealed. |
sealed with abstract |
Not allowed on the same class. |
Errors: deriving from a sealed class is CS0509; overriding a sealed member is CS0239.
Usage notes
- Seal by default for classes not designed for inheritance. Inheritance forces you to keep every virtual call stable, and unsealed public classes are easy to misuse.
- Performance: the JIT can devirtualize calls and turn type checks (
is, casts) into simple pointer comparisons when it knows a class is sealed. The gain is real in hot paths, small elsewhere. - Records: a record can be sealed.
sealed recordalso prevents derived records, andsealed override ToString()stops derived records from regenerating it. - Mocking: many mocking libraries cannot subclass sealed types. Program against an interface if you need test doubles.
- Cannot reverse: adding
sealedto a published class is a breaking change for any code that inherits from it. - Structs and enums are implicitly sealed; the keyword is not allowed on them.
Related
kw-abstract,kw-virtual-override,kw-statickw-record- Tutorials: Inheritance, Polymorphism