How to Prevent Inheritance
In C# you can use the sealed keyword in order to prevent a class from being inherited. Also in VB.NET you can use the NotInheritable keyword to prevent accidental inheritance of the class.
By sealing or NotInheritable a class in .Net environment, you ensure that no class can be derived from that class. In some programming scenarios (mostly used for security reasons ) demand that you should declare your class in such a way that it should not be derived. Typically, it occurs if the functionality that is implemented by the class should not be changed, or more appropriately, overridden. The sole purpose of this class to provide some implementation that can be used within that class only. Moreover a sealed class is the last class in the hierarchy.
You can also use the sealed keyword on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
At any derived level of classes, if you want to prevent next level of inherited classes from overriding a virtual method, then create the method using the keyword sealed along with the keyword override.
.NET framework library
Some of the key classes in the .NET framework library are designed as sealed classes, mainly to limit the extensibility of these classes.
- What is a Class?
- What is an Object?
- Constructors and Destructors
- What Is Inheritance ?
- What are the different types of inheritance ?
- What are Access Modifiers ?
- Why Classes cannot be declared as Protected?
- Can we declare private class in namespace
- Difference between Classes and Structures
- Can we use pointers in C# ?
- Why abstract class can't create instance
- Difference between method Overloading and Overriding
- Difference between Early Binding and Late binding
- What is nested class
- What is partial class ?
- What is Virtual Method
- Difference between class and object
- What is Data Encapsulation?
- Object Based Language and OOPs