How to Prevent Inheritance
Inheritance in .NET allows one class (the derived class) to inherit the members of another class (the base class). However, there may be scenarios where you want to prevent a class from being inherited, effectively disabling inheritance for that class. In .NET, you can achieve this by using the sealed keyword.
The sealed keyword is used to specify that a class or a class member cannot be inherited or overridden by other classes. Here's how you can prevent inheritance using the sealed keyword in .NET:
Preventing Inheritance for a Class
In the example above, the SealedClass is declared with the sealed keyword. This means that other classes cannot inherit from SealedClass, and any attempt to do so will result in a compilation error.
Preventing Inheritance for Class Members
In the example above, the SealedMethod() is declared with the sealed keyword. This means that any derived class cannot override this method. If a derived class attempts to override it, a compilation error will occur.
Preventing inheritance using the sealed keyword ensures that the class or class member cannot be extended or modified, maintaining its intended behavior. It's worth noting that the sealed keyword can only be used with classes that are declared as public, as it doesn't make sense to seal a class that is not accessible from other code.
Here's an example to demonstrate how inheritance prevention works:
In the above example, we attempt to derive a class named DerivedClass from the SealedClass, which is declared as sealed. As a result, a compilation error occurs, preventing the inheritance.