Limiting Extensibility by Sealing Classes 

You can use sealing to limit the ways in which developers can extend your framework. When you seal a class, other classes cannot inherit from it. When you seal a member, derived classes cannot override the implementation of the member. You should not seal types and members by default. Sealing prevents customization of library types and members, and impacts the perception of usability for some developers. In addition, extensibility is one of the fundamental benefits of using an object-oriented framework. You should carefully weigh decisions that restrict this benefit.

Do not seal classes without having a good reason to do so.

Do not assume that because you do not see a scenario in which extending a class would be desirable, that it is appropriate to seal the class. You should seal classes that meet certain conditions:

  • The class is static.

  • The class contains inherited protected members with security-sensitive information.

  • The class inherits many virtual members and the development and testing costs for sealing each member are significantly more costly than sealing the entire class.

  • The class is an attribute that requires fast searching using reflection. Sealing an attribute improves reflection's performance when retrieving attributes.

Do not declare protected or virtual members on sealed types.

If a type is sealed, it cannot have derived classes. Protected members can be accessed only from a derived class and virtual members can be overridden only in a derived class.

Consider sealing members that you override.

You can use this approach to ensure that derived classes do not modify or bypass behavior required for the current class and all derived classes.

Portions Copyright 2005 Microsoft Corporation. All rights reserved.

Portions Copyright Addison-Wesley Corporation. All rights reserved.

For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.

See Also


Unsealed Classes

Other Resources

Design Guidelines for Developing Class Libraries
Designing for Extensibility