Is it always necessary to follow the sealed
keyword with override
in the signature of a method like the below code:
public sealed override string Method1(){.....}
I mean, if I want to "seal" the method within the base class without overriding, is the override
keyword still necessary?
You can't inherit from a sealed class, so no inheritance, no override. The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. When applied to a class, the sealed modifier prevents other classes from inheriting from it.
Sealing a method only makes sense if you override it. What happens here is the following: You are overriding a method from a base class ( override ) and tell the compiler that classes derived from your class are no longer allowed to override this method ( sealed ).
A method can also be sealed, and in that case, the method cannot be overridden. However, a method can be sealed in the classes in which they have been inherited. If you want to declare a method as sealed, then it has to be declared as virtual in its base class.
sealed (C# Reference) You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
Sealing a method only makes sense if you override it.
What happens here is the following:
You are overriding a method from a base class (override
) and tell the compiler that classes derived from your class are no longer allowed to override this method (sealed
).
If the method is a new one declared by you in your class and you want to prevent derived classes from overriding it, simply don't declare it as virtual.
If the method is declared in a base class but is not overridable sealing it wouldn't make any sense, because it already can't be overriden.
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