2

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?

Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112

4 Answers4

9

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.

Jared Shaver
  • 1,339
  • 8
  • 12
5

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.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
2

Classes with sealed or static keyword, valuetypes cannot be used in almost all situations. Also you may look for similar questions on SW, like this

Community
  • 1
  • 1
Lonli-Lokli
  • 3,357
  • 1
  • 24
  • 40
1

From MSDN's Abstract and Sealed Classes and Class Members (C# Programming Guide):

public sealed class D
{
    // Class members here.
}

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.

This one if from MSDN's MustInherit and NotInheritable Classes

NotInheritable Class A
End Class

Class B
    ' Error, a class cannot derive from a NotInheritable class.
    Inherits A
End Class

A NotInheritable class is a class from which another class cannot be derived. NotInheritable classes are primarily used to prevent unintended derivation.

In this example, class B is in error because it attempts to derive from the NotInheritable class A. A class can not be marked both MustInherit and NotInheritable.

tymtam
  • 31,798
  • 8
  • 86
  • 126