Abstract class versus calling base

I need to give the user some degree of control over a function. So I want to partially implement a class that the user can fully implement. I came up with this solution.

public abstract class A
{
    protected void FunctionA()
    {
        // My implementation here
        FunctionB();
    }

    protected abstract void FunctionB();
}

public class B : A
{
    protected override void FunctionB()
    {
        // User implementation here
    }
}

      

Another solution is

public class A
{
    protected virtual void FunctionB()
    {
        // My implementation here
    }
}

public class B : A
{
    protected override void FunctionB()
    {
        base.FunctionB();
        // User implementation here
    }
}

      

Is there some reason why I should use one of these solutions over the other? Does it provide any advantage? Can anyone give me some idea of ​​when I should use one solution and not the other?

+3


source to share


1 answer


Your first solution is actually a well known pattern called Template Method Pattern . This is a good approach if you want to make sure the underlying method is executed (because it FunctionA

can do other things besides being called FunctionB

).



In the second solution, it becomes possible that the override method does not call the base method. This may or may not be appropriate depending on your scenario.

+4


source







All Articles