Previous Page
Next Page

Sealed Classes

Using inheritance is not always easy and requires forethought. If you create an interface or an abstract class, you are knowingly writing something that will be inherited from in the future. The trouble is that predicting the future is a difficult business. It takes skill, effort, and knowledge of the problem you are trying to solve to craft a flexible, easy-to-use hierarchy of interfaces, abstract classes, and classes. To put it another way, unless you consciously design a class with the intention of using it as a base class, it's extremely unlikely that it will function very well as a base class. Fortunately, C# allows you to use the sealed keyword to prevent a class from being used as a base class if you decide that it should not be. For example:

sealed class LiteralToken : DefaultTokenImpl, IToken
{
    ...
}

If any class attempts to use LiteralToken as a base class, a compile-time error will be generated. A sealed class cannot declare any virtual methods. The sole purpose of the virtual keyword is to declare that this is the first implementation of a method that you intend to override in a derived class, but a sealed class cannot be derived from.

NOTE
A struct is implicitly sealed. You can never derive from a struct.
Sealed Methods

You can also use the sealed keyword to declare that an individual method is sealed. This means that a derived class cannot then override the sealed method. You can only seal an override method (you declare the method as sealed override).You can think of the interface, virtual, override, and sealed keywords as follows:


Previous Page
Next Page