Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a default method in a base class that's always called before child implementations?

Tags:

c#

oop

C# here - is it possible to have an abstract base class define a method with default behavior, and have this default be called before a child class implementation? For example:

public abstract class Base
{
    public virtual int GetX(int arg)
    {
        if (arg < 0) return 0;
        // do something here like "child.GetX(arg)"
    }
}

public class MyClass : Base
{
    public override int GetX(int arg)
    {
        return arg * 2;
    }
}

MyClass x = new MyClass();
Console.WriteLine(x.GetX(5));    // prints 10
Console.WriteLine(x.GetX(-3));   // prints 0

Basically I don't want to have to put the same boilerplate in every child implementation...

like image 964
queuebob Avatar asked Feb 25 '23 18:02

queuebob


1 Answers

Callable by who would be the question. The way that I've dealt with this issue in the past is to create 2 methods, a public one in the base class and a protected abstract one (perhaps virtual with no implementation) as well.

public abstract class Base
{
  public int GetX(int arg)
  {
    // do boilerplate

    // call protected implementation
    var retVal = GetXImpl(arg);

    // perhaps to more boilerplate
  }

  protected abstract int GetXImpl(int arg);
}

public class MyClass : Base
{
  protected override int GetXImpl(int arg)
  {
    // do stuff
  }
}
like image 192
Peter Oehlert Avatar answered Feb 27 '23 09:02

Peter Oehlert