We recently started an internal academy in our company to improve our software development skills. The first meeting was about OOP fundamentals, it was really interesting (thanks Vesko for your efforts!). This question appeared as interesting for me - when should we use the sealed class. Some collegues guessed it should be used in the most concrete classes, as they will not be used as a base classses, but I don't think so. After all - why should you say : "Hey, don't use this thing as a base class" explicitly after you know it will not be used anyway. I did soem research on the net about the sealed class usage, it appeared it's common use is for classes with static methods. The example I've found was about Brush and Pen .NET |
So when you are doing software you may keep in mind that you have that sealed thing to help you limit the inheritance of your classes.
2 comments:
Hi Pavel,
I am very happy that you liked the task. I will just add my bits to your research.
Jeffrey Richter is in my oppinion one of the deepest divers in the .NET. He has some wonderful books which covers a lot of interesting details of the .NET as a whole. He has written some words for sealed, too:
"When defining a new type, compilers should make the class sealed by default so that the class cannot be used as a base class. Instead, many compilers, including C#, default to unsealed classes and allow the programmer to explicitly mark a class as sealed by using the sealed keyword. Obviously, it is too late now, but I think that today’s compilers have chosen the wrong default and it would be nice if it could change with future compilers. There are three reasons why a sealed class is better than an unsealed class:
Versioning: When a class is originally sealed, it can change to unsealed in the future without breaking compatibility. (…)
Performance: (…) if the JIT compiler sees a call to a virtual method using a sealed types, the JIT compiler can produce more efficient code by calling the method non-virtually.(…)
Security and Predictability: A class must protect its own state and not allow itself to ever become corrupted. When a class is unsealed, a derived class can access and manipulate the base class’s state if any data fields or methods that internally manipulate fields are accessible and not private.(…)"
I will only add that there is another usage of the sealed keyword - when you have virtual method in a base class, when we override this method in a derived class we can override it as override sealed which means that in the inheritors of the second class this method cannot be overriden again.
Thanks!
Post a Comment