Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 355
M.A. Hanin Avatar asked Mar 25 '10 19:03

M.A. Hanin


People also ask

Can sealed class be private?

Sealed classes can be declared directly inside the namespace. We cannot create an instance of a private class.

When should a class be declared as sealed?

Marking a class as Sealed prevents tampering of important classes that can compromise security, or affect performance. Many times, sealing a class also makes sense when one is designing a utility class with fixed behaviour, which we don't want to change.

What is the difference between sealed and private class?

A Private class can only be accessed by the class it is defined and contain within - it is completely inaccessible to outside classes. A Sealed class can be accessed by any class, but can not be derived from.

Can sealed class be public?

Techopedia Explains Sealed Class A sealed class can be useful only if it has methods with public-level accessibility. A sealed class cannot be an abstract class as the abstract class is intended to be derived by another class that provides implementation for the abstract methods and properties.


1 Answers

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

like image 138
JaredPar Avatar answered Sep 23 '22 14:09

JaredPar