6

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

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
enzom83
  • 8,080
  • 10
  • 68
  • 114
  • 2
    You can only seal overridden members. The lack of the keyword `abstract` or `virtual` means that the method is already sealed. – ChaosPandion Aug 15 '12 at 17:49

3 Answers3

8

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Ok, it works correctly by removing the `sealed` keyword, but I thought that there was some mechanism (such as the `final` keyword in Java) that _prevents you from hiding the inherited method_. I wonder, out of curiosity, the reason for which this mechanism is not present. – enzom83 Aug 15 '12 at 19:11
  • 2
    @enzom83: No, you can always *hide* the inherited method - but you can't override it, so anyone calling `TemplateMethod` on an expression of static type `Base` will always call the right method. – Jon Skeet Aug 15 '12 at 19:15
1

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

Jordão
  • 55,340
  • 13
  • 112
  • 144
1

C# methods are sealed by default

log0
  • 10,489
  • 4
  • 28
  • 62