I wrote some not sealed class that contain 3 virtual public method and one private method.
And i make this class public that all my develop group member could use this class ( include inherits and override the virtual public methods ) .
One of the private method name is 'PrivateMethod77()'.
Each time the public method 'PublicMethod77()' is call => the 'PrivateMethod77' is call in the first line of the method implementation ( after this line there are more implication logic ).
I want to keep this logic and 'force' the inherits and override of the method PublicMethod77 to call the PrivateMethod77 method as the first line of the PublicMethod77
Is there a way to do it ?
I don't think that you can enforce the inheriting classes to always first call a method's super implementation, but:
Normally I use a Template method pattern for cases like this:
public abstract class TemplateEnforcer
{
private void TheSame()
{
Console.WriteLine("Everyone calls me;");
}
public void TemplateMethod()
{
this.TheSame();
this.NeedsImplementation();
}
protected abstract void NeedsImplementation();
}
public class TemplateImplementer : TemplateEnforcer
{
protected override void NeedsImplementation()
{
Console.WriteLine("Implemented in TemplateImplementer");
}
}
Code output for this call new TemplateImplementer().TemplateMethod():
//Everyone calls me;
//Implemented in TemplateImplementer
Template method pattern benefits:
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