Frederik Today

Why Classes Should Be Sealed in .Net Explained

The **sealed** keyword prevents coders from inherent your class. A **sealed** class can not be used as a base class.

Why would you block the inheritance feature of a class?

  • When a class is originally sealed, it can change to unsealed in the future without breaking compatibility.
  • Performance
  • Security: Most classes are not written well to be inherent. When a class can be inherited, the derived class can access and manipulate the state of the base class.

Are Sealed classes faster?

Yes, the compiler can add some run-time optimizations, which can make calling sealed class members slightly faster.

How to seal a class?

Add the sealed keyword in front of the class
public sealed class Class
{
// Class members here.
}

Can an abstract class be sealed in C#?

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class.

An abstract class is designed to be inherited by subclasses that either implement or override its methods. An abstract class can not be instantiated. The opposite of a sealed class.

Sealed in VB.NET?

The equivalent of sealed in VB.NET is NotInheritable and use exactly the same way.

Conclusion, Should all classes be sealed C#?

To code better, you should by default seal all your classes, based on all the positive reasons explained above. it is much easier to "unseal" the class in a later stage, allowing inheritance, equivalent blocking the inheritance and getting in compatibility trouble.