NotInheritable
KeywordThere are situations in which you might want to prevent inheritance from your classes. This can be useful if you do not want a client to modify in any way the base object’s behavior and its members. To accomplish this, you simply need to mark a class with the NotInheritable
keyword. The following code shows an example of a class that cannot be derived:
As you can see, the BusinessPerson
class is marked as NotInheritable
and cannot be derived by other classes. It can still inherit from other classes but, obviously, members cannot be marked as Overridable
, being not inheritable. Another typical example of not inheritable classes is when you have a class exposing only shared members, as shown in the following code:
The class is also decorated with the CLSCompliant
attribute because such a situation is explicitly established by the Common Language Specification. NotInheritable
is the Visual Basic counterpart of the sealed
keyword in Visual C#. It’s important to know also the C# representation, because in .NET terminology not inheritable classes are defined as sealed and many analysis tools use this last word. NotInheritable
classes provide better performance; the compiler can optimize the usage of this kind of classes, but obviously you cannot blindly use classes that cannot be inherited only to avoid a small overhead. You should always design classes that fit your needs.
As a better programming practice, developers should always mark classes with NotInheritable
unless they explicitly plan for the class to be inheritable by a consuming class.
3.138.118.103