Search code examples
.netoptimizationcompilationcilsealed

Are private classes being sealed at compilation?


Assume the following: we have class B, which is a private class nested inside class A. There isn't any class inheriting from class B. The question is: will the compiler automatically mark class B as Sealed? (NonInheritable in VB). Is there any good reason for the compiler not to mark class B as sealed?

My line of thought is this: since class B is nested inside class A and is private, and there is no other class inheriting from class B, it should be safe to seal it, because it can't be inherited outside class A (not even by subclasses of A).

Class A
    Private Class B  
    End Class
End Class

Solution

  • The compiler will not automatically mark this type as sealed.

    True in this very specific scenario there is no real value in leaving the class as unsealed. However determining that you are in this scenario is not always so easy. You have to consider the following

    • The type is private
    • Must consider the presence of partial classes
    • Other private nested types could inherit.

    These are not impossible to calculate but it's not trivial either. It's much cheaper to ask the user to just seal the type themselves