Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why seal a class?

I'd like to hear what is the motivation behind the bulk of sealed classes in the .Net framework. What is the benefit of sealing a class? I cannot fathom how not allowing inheritance can be useful and most likely not the only one fighting these classes.

So, why is the framework designed this way and wouldn't it be unbreaking change to unseal everything? There must be another reason than just being evil?

like image 778
mmiika Avatar asked Nov 06 '08 10:11

mmiika


People also ask

Why would you seal a class?

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 does Seal class A mean?

Techopedia Explains Sealed ClassA 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.

Why we should use sealed class in C#?

We use sealed classes to prevent inheritance. As we cannot inherit from a sealed class, the methods in the sealed class cannot be manipulated from other classes. It helps to prevent security issues.


2 Answers

Classes should either be designed for inheritance or prohibit it. There is a cost to designing for inheritance:

  • It can pin down your implementation (you have to declare which methods are going to call which other methods, in case a user overrides one but not the other)
  • It reveals your implementation rather than just the effects
  • It means you have to think of more possibilities when designing
  • Things like Equals are hard to design in an inheritance tree
  • It requires more documentation
  • An immutable type which is subclassed may become mutable (ick)

Item 17 of Effective Java goes into more details on this - regardless of the fact that it's written in the context of Java, the advice applies to .NET as well.

Personally I wish classes were sealed by default in .NET.

like image 56
Jon Skeet Avatar answered Oct 23 '22 09:10

Jon Skeet


  • Sometimes classes are too precious and not designed to be inherited.
  • Runtime/Reflection can make inheritance assumptions about sealed classes when looking for types. A great example of this is - Attributes are recommended to be sealed for lookup runtime speed. type.GetCustomAttributes(typeof(MyAttribute)) will perform significantly faster if MyAttribute is sealed.

The MSDN article for this topic is Limiting Extensibility by Sealing Classes.

like image 24
CVertex Avatar answered Oct 23 '22 07:10

CVertex