Search code examples
.netkeywordsealed

Why does the 'sealed' keyword exist in .Net?


A large number of classes in the .Net framework are marked as 'sealed', preventing you from inheriting those classes with your own. Surely this goes against the nature of object orientation, where you can extend and redefine the behaviour of existing objects.

Is there a good reason for the existence of the 'sealed' keyword?

As an example, NotifyCollectionChangedEventArgs in Silverlight is sealed. I wanted to create my own version of ObservableCollection that supported AddRange and RemoveRange, but the Silverlight version of NCCEA doesn't provide a constructor that supports multiple items for the NewItems and OldItems properties, which are already defined as ILists. Usually, I'd just extend the class with my own variant that overrode the NewItems and OldItems properties, but in this case I can't and I can see no reason why that should be the case.


Solution

  • Designing classes (or frameworks) to be extensible isn't trivial, and put simply inheritance is not the single principle of Object Oriented programming.

    So sealed exists to allow the developer / designer to express and preserve those intentions. Sealing a class can also make their life easier by reducing the maintenance burden. It allows the original developer to control how the class (or framework) is extended, so they can make internal changes without worrying about breaking changes to others code.

    One principle is that developers should seal any leaf classes by default. Then, when the developer creates an unsealed class intentionally, it forces them to think about extensibility.


    Ref: Eric Lippert - Why Are So Many Of The Framework Classes Sealed?