What is Sealed Class ?
Why to use Sealed Class ?
Where Sealed Classes are used ?
I have been ever wondered and hesitate to make a practice of using “sealed” keyword with each and every class other than un-sealed type (except classes that is to be inherit/derived). I went through many articles, blogs, and tips and found diverse view on regular usage of “sealed” type.
Some advocate for using it for –
- It speeds as it JIT compiler works efficiently with non-virtual methods.
- It prevent future coming problem by restricting inheritance for those classes that are not meant for derived. A compile time checking and error is generated for type-safety. This advocate “Always declare a new class as sealed …” Ref: http://www.codeproject.com/Articles/239939/Csharp-Tweaks-Why-to-use-the-sealed-keyword-on-cla
- Type safety: by not allowing sealed classes to be generic type constraints/arguments.
Some suggests for not using “sealed” unless it is very much required :
- It doesn't so much make efficient and can't easily noticed, so need to bother about speed of JIT.
- It makes burden on programmer.
More points to note with respect to “sealed” class:
- A sealed class can't be a base class for other class. è So sealed class can't be an “abstract” class.
- Sealed method should be avoided for just stopping override. We can use “virtual” keyword for this purpose.
- An overridden method can be “sealed” and thus it will fix this version as a final and no further overriding can be done.
- Sealed can be used to prevent extension of existing classes so that outsiders/third person can't extend the functionality using our class.
- Modifier abstract can't used with a “sealed” class. (Structs are implicitly “sealed” hence they can't be inherited.)
- Common methods, utility methods can be written in a sealed class.