How do you prevent a class from overriding in .NET?You can prevent
a class from being overridden. This is possible by using a keyword. In
C# you will be using the keyword sealed to prevent overriding and in VB.NET
you will be using the keyword NotInheritable to achieve the same. Here
is an example to demonstrate both of them: Prevention of Class Overriding in C# Using sealed Keyword: Usage of sealed keyword is demonstrated in the example shown below: public sealed class sealedClass { public void displayMsg() { Console.WriteLine(In Sealed Class ); } } class derivedClass : sealedClass { public displayMsg() { Console.WriteLine(In Derived Class ); } } In this example,
you have defined the class sealedClass as sealed. You try to inherit sealedClass
using the derivedClass and define/override the method displayMsg of sealedClass.
You have also defined the class testClass. Then you have created an instance
of derivedClass inside Main method of testClass. Now try compiling this
code, you will end up in the following error: In this example, you have used sealed keyword on a class and ensured that the class cannot be overridden or inherited. C# also provides a provision to prevent overriding of a specific method in the class by specifying the sealed keyword along with the method signature instead of specifying sealed keyword along with the class name. Prevention
of Class Overriding in VB.NET Using NotInheritable Keyword: Module sampleModule Public NotInheritable
Class sampleClass This example
will work fine and it will print the following output in the console: Problem arises
when you try to inherit this class sampleClass which is marked as NotInheritable.
Consider that the following class is added into your program: Now your
program will not compile and you will end up in the following error:
FREE
Subscription
Subscribe
to our mailing list and receive new articles Note
: We never rent, trade, or sell my email lists to Visit
.NET Programming Tutorial Homepage ______________________________________________________ |