I know that I can use the sealed in order to prevent other classes to inherit a certain class, but is it possible to allow inheritance but prevent overriding of some virtual methods?
To prevent being overridden, use the sealed in C#. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.
Remember, though syntactically you can use private, static and final modifier to prevent method overriding, but you should always use final modifier to prevent overriding. final is best way to say a method is complete and can't be overridden.
3. Which of the given modifiers can be used to prevent Method overriding? Explanation: When an instance method declaration includes the sealed modifier, the method is said to be sealed method. It means a derived class cannot override this method.
Only virtual
methods can be overridden.
Just leave out virtual
, and your method will not be overridable.
you can also use sealed modifier to prevent a derived class from further overriding the method.
check this out: Sealed methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With