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...
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
}
}
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