Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the Template Method pattern in C#

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#)?

like image 529
enzom83 Avatar asked Aug 15 '12 17:08

enzom83


2 Answers

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 the sealed modifier, it must also include the override modifier. Use of the sealed modifier prevents a derived class from further overriding the method.

like image 110
Jon Skeet Avatar answered Sep 18 '22 10:09

Jon Skeet


Just remove the sealed keyword. By default, methods are not overridable; subclasses cannot override them, only hide them.

like image 33
Jordão Avatar answered Sep 20 '22 10:09

Jordão