What type of class cannot be inherited? Why and how this can be done? Kindly explain with examples.
Also What are the possible ways to prevent a class from being derived?
Class that are marked with the sealed (C#) or NotInheritable (VB.NET) keywords cannot be inherited from. This is done at the definition of the classes. The most commonly used sealed class is System.String.
Obviously, the sealed keyword can prevent anyone from deriving from a type. But you can also control who can derive from your class by changing the visibility of your constructors. If you declare all constructors internal (including the default) then only other classes in the same assembly will be able to derive. If you declare them private (again, including the default), then only a nested class inside your class would be able to.
There are some special cases like System.Delegate and System.ValueType which have publicly visible constructors but you cannot derive from them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With