Common Type System—Sealing Types and Methods
Sealing Types and Methods
A type can be marked as sealed meaning that no further derived types can be created. The C# surfaces
this feature with the sealed keyword:
sealed class Foo {}
No subclasses of Foo can be created. All custom value types are implicitly sealed due to the restriction
that user defined value types cannot be derived from.
Also note that a type which is both sealed and abstract can by its very definition never have a concrete instance. Therefore, these are considered static types, in other words types that should only have static members on them. The C# language keyword for static classes uses this very pattern in the IL, that is, these two lines of code are semantically equivalent:
static class Foo { /*...*/ } abstract sealed class Foo { /*...*/ }
The C# compiler conveniently ensures that you do not accidentally add instance members to a static class, avoiding creating completely inaccessible members.
Individual virtual methods can also be sealed, indicating that further overriding is not legal. Further, derived types may still hide the method through newslotting, however, for example:
class Base { protected virtual void Bar() { /*...*/ } } class Derived : Base { protected override sealed void Bar() { /* ... */ } }
In C#, the sealed keyword is used to seal methods. In the above example, it means that subclasses of
Baz cannot override the method Bar.
|

