The template method pattern provides that the abstract base class has a not overridable method: this method implements the common algorithm and should not overridden in the subclasses. In Java the template method is declared final
within the abstract base class, in C# the sealed
keyword has a similar meaning, but a not overridden method can not be declared sealed
.
public abstract class Base
{
protected abstract AlgorithmStep1();
protected abstract AlgorithmStep2();
public sealed void TemplateMethod() // sealed: compile error
{
AlgorithmStep1();
AlgorithmStep2();
}
}
How can I solve this problem? Why can not prevent a method can be overridden by subclasses (in C#)?
The sealed
modifier is only valid for function members which are overriding base class members, to stop them from being virtual for derived classes. Function members are non-virtual by default in C# (unlike Java). You still need the sealed
modifier for a class though - classes aren't sealed by default.
Just remove the sealed
modifier from your method and it should be fine.
See section 10.6.5 of the C# 4 spec for more details about sealed methods (sealed properties and events are in section 10.7.5 and 10.8.4 respectively).
When an instance method declaration includes a
sealed
modifier, that method is said to be a sealed method. If an instance method declaration includes thesealed
modifier, it must also include theoverride
modifier. Use of thesealed
modifier prevents a derived class from further overriding the method.
Just remove the sealed
keyword. By default, methods are not overridable; subclasses cannot override them, only hide them.
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