What is the best way to implement a strategy for the constructor of a template/abstract class in C#? I have several classes which are all based on parsing a string inside the constructor. The parsing is done in a static method which creates list of key value pairs and is common for all classes, but some fields are also common for all classes – thus I use a abstract template class.
The problem is that I do not see a way to inherite the implementation of the constructor of the abstract base class. Otherwise I would implement the constructor strategy in the base class and would force the handling of the lists inside some abstract methods.
Edit: Added Not working code for the template class
public abstract class XXXMessageTemplate { public XXXMessageTemplate(string x) // implementation for the constructor { Parse(x);//general parse function CommonFields();//filling common properties HandlePrivateProperties();//fill individual properties HandlePrivateStructures();//fill individual structures } abstract void HandlePrivateProperties(); abstract void HandlePrivateStructures(); } The actual messages should not implement any constructor and only implement the HandlePrivateProperties and HandlePrivateStructures functions.
If you want the logic of the base class constructor to run in the derived class, you’d normally just call up to it:
The base class can call abstract/virtual methods during the constructor, but it’s generally frowned upon as the derived class’s constructor body will not have been executed yet. (You’d want to document this really emphatically.)
Does this answer your question? I’m not entirely sure I understand the issue – some pseudo-code would help.
EDIT: The derived classes have to implement constructors. Constructors aren’t inherited. If you don’t specify any constructor, the compiler will provide a parameterless constructor which calls a base parameterless constructor. However, you can easily write a constructor with the same signature and just call the base class constructor: