How to Prevent Inheritance

How to Prevent Inheritance  in C# VB.Net

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.


sealed class MyClass {}


NotInheritable Class MyClass End Class

Sealed Classes

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.

Sealed Methods

Sealed Classes Sealed Methods  in C# VB.Net

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.

class myClass { protected virtual void display() { } } class newClass : myClass { sealed protected override void display() { } }

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

C#  Interview questions and answers VB.Net

Some of the key classes in the .NET framework library are designed as sealed classes, mainly to limit the extensibility of these classes.