sealed
keyword for methods to block hidden overrwrites without new
from happening
#8158
Replies: 4 comments 1 reply
-
IMO, you already have the mechanism to control this by making those warnings into errors. For a case where you want to allow hiding without |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
I don't think so, because if the base class's non-virtual method is called, it doesn't make any difference whether any derived types exist which have
I hate to be that guy, but an analyzer would work great for this.
Are you worried that a child class's
If |
Beta Was this translation helpful? Give feedback.
-
This pattern is very common in BCL (
Even with this proposal, it doesn't prevent accidental explicit implementation in child class. The method implementing an interface doesn't necessarily have the same name. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Problem
Currently when writing new methods with inherited class we are allowed to "overwrite" methods with the same signature as is.
Right now, this code will happily compile although will result in 2 warnings.
CS0108
&CS0114
.We can set those warnings as errors, but there might be moments where such behaviour would be wanted (without
new
keyword)Idea
My idea here would be to add
sealed
keyword to any method in order to forcenew
keyword when hiding base methods, or even outright block it from overwriting/hiding. There might be possible performance benefits toseal
methods if compiler can for sure know that we cannot usenew
keyword in given context.Thoughts
Benefits of
sealing
methods like that would allow programmers to make conscious decisions on when they want to "lock" method signature from being overwriten/hidden.I personally would use this in the following context. Having interface that requires method
Test
but I want to perform some actions before/after the final implementation of the method. So I would implementTestToInherit
method that would be abstract and implemented in all children of the base class.This would allow me to write consistent code and be conscious of all the implications that come with
sealing
a method. I am aware ofsealed virtual
but this doesn't prevent from accidental hiding in child class. Also not having to worry about overwritingvirtual
methods and remembering to callbase
methods.This would also be beneficial to when we want to use Reflection to call those methods by
name
(for some reason). We can assure that this method is always one and true to the base class, and that child classes do not overwrite it's behaviour (accidental or on purpose).Beta Was this translation helpful? Give feedback.
All reactions