When and why do you seal the class?

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

+49
c # oop c ++ - cli
Oct. 15 '11 at 11:40
source share
3 answers

1) In a class that implements security functions, so that the original object cannot be "personified."

2) More generally, I recently exchanged with a person at Microsoft who told me that they tried to limit inheritance to places where it really was fully, because it becomes expensive if left untreated.
The sealed keyword tells the CLR that there is not yet a class for finding methods, and this speeds up work.

In most market productivity tools, you will now find a check box that seals all your classes that are not inherited.
Be careful, because if you want to allow plugins or assembly detection through MEF, you will have problems.

+60
Oct. 15 '11 at 11:54
source share

In addition to Baboon, the excellent answer is:

3) If the class is not intended to be inherited, subclasses may violate class invariants . This is really only applicable if you are creating a public API, but as a rule, I will seal any class that is clearly not intended for a subclass.

In the corresponding note, applicable only to unsealed classes: any virtual method created is an extension point, or at least looks like an extension point. Declaring virtual methods should be a conscious decision. (In C #, this is a conscious decision; in Java, it is not.)




EDIT : some relevant links:

Also note that Kotlin closes classes by default; its open keyword is the opposite of Java final or sealed for C # . (Of course, there is no universal agreement that this is a good thing .)

+7
May 20 '16 at 12:27
source share

I think this post has a good point of view, a specific case was to try to apply an unsealed class to any random interface, the compiler does not throw an error; but when printing is used, the compiler throws an error that it cannot convert. A sealed class provides added security for code access.
https://www.codeproject.com/Articles/239939/Csharp-Tweaks-Why-to-use-the-sealed-keyword-on-cla

-one
May 18 '17 at 16:16
source share



All Articles