Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of classes cannot be inherited in .NET?

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?

like image 739
Rohit Vipin Mathews Avatar asked Dec 01 '25 05:12

Rohit Vipin Mathews


2 Answers

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.

like image 135
Jared Shaver Avatar answered Dec 03 '25 19:12

Jared Shaver


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.

like image 32
Mike Zboray Avatar answered Dec 03 '25 19:12

Mike Zboray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!