In my opinion, the currently accepted answer is too dogmatic.
The fact is that when you do not mark a method as virtual , others cannot override its behavior, and when you mark a class as sealed , others cannot inherit from the class. This can cause significant pain. I don’t know how many times I have cursed the API for marking sealed classes or not marking virtual methods simply because they did not expect my use.
Theoretically, this may be the right approach, allowing you to only redefine methods and inherit classes that should be overridden and inherited, but in practice it is impossible to predict all possible scenarios, and there really is no good reason to be so closed in.
- Unless you have a good reason, do not put classes as
sealed . - If your library is intended to be consumed by others, try tagging the main methods of the class that contain
virtual behavior.
One way to make a call is to look at the name of a method or property. The GetLength () method in List does exactly what the name implies, and this does not allow significant interpretation. Changing its implementation will probably not be very transparent, so you probably don't need to designate it as virtual . Marking the Add method as virtual is much more useful since someone can create a special List that accepts only certain objects using the Add method, etc. Another example is user controls. You would like to make the basic drawing method virtual so that others can use the bulk of the behavior and just change the look, but you probably won't override the X and Y properties.
In the end, you often do not need to make this decision right away. In an internal project where you can easily change the code, I would not worry about these things. If you need to override a method, you can always make it virtual when that happens. On the contrary, if the project is an API or a library that is consumed by others and is slowly being updated, then it is certainly worth considering which classes and methods can be useful. In this case, I believe that it is better to be open rather than strictly closed.
Patrick Klug Jan 29 '13 at 0:10 2013-01-29 00:10
source share