5

It seems like there are some real benefits to be gained by marking classes as sealed:

  1. Performance in some cases
  2. Compile-time type safety in other special cases Explicit conversion fails for sealed class
  3. Preventing unintended inheritance of your classes

And there seems relatively little in the way of disadvantages...you can unseal a class without breaking code, but you can't later seal a class that was unsealed without breaking code.

Is it best practice to always mark a class sealed unless you intend for it to be inherited from? Why or why not?

Any other comments or guidance on this topic?

richard
  • 12,263
  • 23
  • 95
  • 151
  • 5
    http://stackoverflow.com/questions/2164170/should-i-seal-all-classes-i-know-shouldnt-ever-be-used-as-a-base-class – TGH Oct 28 '13 at 04:42
  • I like the answer on that link by eric lippert. That's good enough for me. – richard Oct 28 '13 at 05:00

1 Answers1

2

I think one of the major advantage of using Sealed class is the performance. the JIT compiler can produce more efficient code by calling the method non virtually.However you can argue that performance gain depends upon the algorithm used.

Making a class seal makes it impossible to inherit it and override it's members thus making an controlled environment for execution. However on the other hand overriding members of the class which were not designed to be overriden may produce unexpected results

Classes should be sealed by default however many compilers dont do so, we have to explicitly mark them

Refer

Rambling on the sealed Keyword

Why to use the Sealed Keyword

Rohit
  • 10,056
  • 7
  • 50
  • 82