156

In C# and C++/CLI the keyword sealed (or NotInheritable in VB) is used to protect a class from any inheritance chance (the class will be non-inheritable). I know that one feature of object-oriented programming is inheritance and I feel that the use of sealed goes against this feature, it stops inheritance. Is there an example that shows the benefit of sealed and when it is important to use it?

6 Answers 6

162
  1. On a class that implements security features, so that the original object cannot be "impersonated".

  2. More generally, I recently exchanged with a person at Microsoft, who told me they tried to limit the inheritance to the places where it really made full sense, because it becomes expensive performance-wise if left untreated.
    The sealed keyword tells the CLR that there is no class further down to look for methods, and that speeds things up.

In most performance-enhancing tools on the market nowadays, you will find a checkbox that will seal all your classes that aren't inherited.
Be careful though, because if you want to allow plugins or assembly discovery through MEF, you will run into problems.

9
  • 3
    I meant be careful with sealing classes in reused libraries, especially if they're beind reused by third parties and then reintegrated (via MEF) into the codebase. Your codebase may not inherit a given class but third parties will. Commented Feb 12, 2015 at 11:32
  • 27
    The reason #1 sounds vague but, assuming we don't write "security features" most of the time, does that mean reason #1 hardly applies? Reason #2 is for performance-tuning. How much performance difference are we talking about? Are they significant enough to justify altering a non-security class's definition? Even if the answer would be "yes", this would ideally be a compiler option i.e. "generate optimized code for all non-sealed classes", rather than having us developers to alter code base.
    – RayLuo
    Commented May 2, 2017 at 21:15
  • 3
    it becomes expensive performance-wise if left untreated is this even measureable with less then an insane number of crazy tests?
    – t3chb0t
    Commented Aug 11, 2017 at 12:18
  • 19
    Sealing sucks. It makes testing harder - I would like to mock a couple ASP.NET classes with FakeItEasy, but I can't because they're sealed. Commented Mar 10, 2019 at 22:06
  • 5
    Can't agree more with @RayLuo. I hit it several times that people sealed their classes where security and performance is not really a problem. Their "sealed" simply prevented my reasonable need of overriding the classes, made things much more difficult. Like Warlike Chimpanzee said, mocking a class is so common in testing.
    – ZZY
    Commented May 21, 2019 at 2:58
31

An addendum to Louis Kottmann's excellent answer:

  1. If a class isn't designed for inheritance, subclasses might break class invariants. This really only applies if you're creating a public API, of course, but as I rule of thumb I seal any class not explicitly designed to be subclassed.

On a related note, applicable to unsealed classes only: any method created virtual is an extension point, or at least looks like it should be an extension point. Declaring methods virtual should be a conscious decision as well. (In C# this is a conscious decision; in Java it isn't.)

And then there's this:

  1. Sealing can make unit testing more difficult, as it prohibits mocking.

Some relevant links:

Also note that Kotlin seals classes by default; its open keyword is the opposite of Java's final or the sealed of C#. (To be sure, there is no universal agreement that this is a good thing.)

3
  • 57
    Sealing classes causes more headache than benefit. I've continually found situations where developers have sealed classes, causing me hours of difficulty in what should be simple. Stop sealing classes, you're not as witty as you think you are. Seal classes only if you MUST, and even then, reconsider. Just my opinion, as the guy who has to deal with other people's sealed classes that I cannot edit/unseal. Commented Oct 4, 2016 at 20:19
  • 16
    @GantMan 's comment should actually be considered as one of the answer to the OP's question, because it essentially gives an answer as "When? Hardly. Why? This is the reason of why you do NOT do that." Grant you should re-post your comment as a separated answer and then collecting votes for it. :-)
    – RayLuo
    Commented May 2, 2017 at 21:19
  • 2
    Was this refferrng to this answer: stackoverflow.com/a/7777674/3195477 ? Its better to link to it than (only) name the person Commented May 22, 2020 at 13:20
3

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.

For example, System namespace in C# provides many classes which are sealed, such as String. If not sealed, it would be possible to extend its functionality, which might be undesirable, as it's a fundamental type with given functionality.

Similarly, structures in C# are always implicitly sealed. Hence one cannot derive one structure/class from another structure. The reasoning for this is that structures are used to model only stand-alone, atomic, user-defined data types, which we don't want to modify.

Sometimes, when you are building class hierarchies, you might want to cap off a certain branch in the inheritance chain, based on your domain model or business rules.

For example, a Manager and PartTimeEmployee are both Employees, but you don't have any role after part-time employees in your organization. In this case, you might want to seal PartTimeEmployee to prevent further branching. On the other hand, if you have hourly or weekly part-time employees, it might make sense to inherit them from PartTimeEmployee.

13
  • 3
    How would extending the String class be undesirable? String would still work exactly how it currently does, and you could have a derived class with additional functionality when that is desired, so what issue are you talking about?
    – Kevin
    Commented Jan 14, 2019 at 18:59
  • 2
    Also what would be the point of "capping" your inheritance hierarchy? It would mean that if you ever did need to extend that hierarchy you would have to unseal the parent class first, which is just inefficient
    – Kevin
    Commented Jan 14, 2019 at 19:00
  • 1
    Check out this excellent post from Eric Lippert and this SO question. Commented Jan 14, 2019 at 19:12
  • 2
    Even that answer basically boils down to "Why would you want to derive String?", then goes on to mention reasons why you might want to derive String (null-terminated strings for instance) and says you should just work around it without inheritance. So why make it more complicated and have to work around it later when you can simply leave it unsealed in the first place and leave your options open
    – Kevin
    Commented Jan 14, 2019 at 19:17
  • 2
    My inner skeptic sees an article posted in 2004 and is curious is Eric's thoughts may have evolved over the last 15 years. EDIT: Well, at least MS official stance has, per the very link you referenced.
    – chill94
    Commented Aug 29, 2019 at 19:20
2

I think this post has some good point, the specific case was when trying to cast a non-sealed class to any random interface, compiler doesn't throw error; but when sealed is used the compiler throws error that it can't convert. Sealed class brings additional code access security.
https://www.codeproject.com/Articles/239939/Csharp-Tweaks-Why-to-use-the-sealed-keyword-on-cla

3
  • 1
    A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.
    – Baum mit Augen
    Commented May 18, 2017 at 23:16
  • Sorry I didn't intend to post it as answer, but it seems not related to other answers and I don't know where to put it Commented May 19, 2017 at 2:57
  • 1
    I edited the post according to the suggestion. Originally I just would like to contribute a different angle (perhaps), but I only got a downvote and we didn't talk about the content yet, could the -1 kindly let know the reason? Commented May 19, 2017 at 4:37
2

Sealing is a conscious decision that should be considered only when you want to clearly reveal your intent about the structural characteristics of your class. It is a structural choice about your object model. It should never be a decision about performance, or security(**). But more importantly, never about arbitrary limits to your inheritance tree.

I am putting forward this rule of thumb: A class should never be sealed if you have to think whether it is a good idea to seal it. A decision to seal a class should be obvious to you and will be made even before you write the class's first line of code.

As an example, since we can't derive from them but they look so much like a regular class, we often think of structs as sealed classes. Which is what they are. It is this limitation that allows them to implement value-type semantics since inheritance and polymorphism can only work with reference types. So the "struct class" is sealed because any class that implements value-type semantics must give away inheritance and have its memory managed differently. (Note that this is true of any value-type object in C#, not just structs).

Another example: A code generator may write a sealed class representing a window and all its elements for the user to define the behavior on, because the UI engine expects this class, and no other, in order to be able to render the window.

And last example: A math utility class may be sealed because it is built around truisms, and any extended behavior can never be correct or "work as intended". This is one example that doesn't exactly fall under the rule of thumb above. Never blindly trust rules of thumb.


(**) If performance is an issue in your application, you can be sure unsealed classes are not the reason. Similarly, if you depend on sealed classes to enforce security in your application, the problem must be on your base classes -- what they expose or allow to be extended.

0

If your design pattern is using singletons, you would want to seal the class so that only 1 instance can ever be created. Basically, seal the class, create a private constructor, and public static method to return the class.

2
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Apr 17, 2023 at 5:56
  • 1
    Wrong answer. Sealed keyword has nothing to do with limiting the number of instances. Since you refers to the singleton design pattern, are you confusing with the static keyword ?
    – Poilaupat
    Commented Feb 2 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.