In C#, can you prevent a class from being inherited by another class? If so, how do you do it? And why would you want to do it?
In C#, can you prevent a class from being inherited by another class? If so, how do you do it? And why would you want to do it?
6 Comments so far
Leave a comment
This can be done by making constructors of the class private and making use of Named constrcutors for the class
By say it on 06.28.07 2:07 am | Permalink
In C# the proper way to prevent a class from being inherited is to use the “sealed” modifier.
Sealed classes
By Rodneyk on 02.04.08 9:18 am | Permalink
try the ’sealed’ keyword on the class definition.
sealed class CantInheritMe {}
By JR on 07.02.08 9:44 am | Permalink
The above comment is incorrect. Making a class constructor private will not prevent a class from being inherited by another class, it would simply prevent it from being instantiated. The desired functionality would be accomplished by using the “sealed” keyword in the class declaration. (i.e. public sealed class MyClass).
The sealed modifier is primarily used to prevent unintended derivation, such as when a class contains a concrete implementation of an abstract base. In this case the developer of the sealed class would want other implementations to inherit from the abstract base class and instead of inheriting from the sealed concrete implementation. It also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations.
By Nate on 04.08.09 5:30 pm | Permalink
Yes, use the sealed modifier as follows:
sealed class NotInheritable { … }
You would use this to prevent unintential inheritance, or for run-time optimization.
By Ashley Visagie on 04.28.09 9:46 pm | Permalink
This can be done by declaring the class as a sealed class.
By radliwag on 08.16.09 8:14 am | Permalink
Leave a comment
If you are including code in your comment, place it within a <div class='code'></div> tag for better formatting.