I have a number of tasks which can be carried out by similar (yet slightly different) classes which all share a common set of functionality.
My intention is to extract this functionality into a parent class, and because I don't want this to be implemented itself I've marked it abstract
.
However all of the calling classes call a single method - which used to contain the extracted common functionality. I don't want to override
the parent class method but I want it to be executed in addition to what is defined in the child class.
I initially thought this was a job for a partial method, but I think this will break semantics somewhat. So what is the best way forward for me? Experiencing a bit of tunnel vision here.
You could do it like this:
public abstract class Parent
{
public void TheSingleMethod()
{
CommonFunctionality();
InternalDo();
}
protected abstract void InternalDo();
private void CommonFunctionality()
{
// Common functionality goes here.
}
}
public class Derived : Parent
{
protected override void InternalDo()
{
// Additional code of child goes here.
}
}
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