Home > Software engineering >  defining part of a method in a parent class without defining the return
defining part of a method in a parent class without defining the return

Time:11-29

Can I have a base class with something similar to a virtual method that declares some partial functionality, but does not return anything, in such a way that inherited classes will execute that functionality and then proceed to return something?

Simplified example:

    class Parent
    {
        float baseFloat;  
        public virtual void MyMethod()
        {
            baseFloat = 3.14f;
        }
    }

    class Child : Parent
    {
        public override float MyMethod()
        {
            base.Method();
            return 6.28f;
        }
    }

Of course this will error because the overridden method has return type float vs void. The reason I want this is that I can be sure that all derived classes will want the analogous code to baseFloat = 3.14f; which modifies a class variable, but they will have their own implementations of return 6.28f;. So currently I am copy pasting the repeating code into all derived classes, but it would be nice to just implement that once in the base class.

Thanks

CodePudding user response:

[...] in such a way that inherited classes will execute that functionality and then proceed to return something?

If you look at it the other way around, you could let the method in the parent class be non-virtual and return a float, and let that method return the value of a protected virtual property that every inheriting class overrides:

class Parent
{
    float baseFloat;
    
    protected virtual float MyMethodOutput => 0;

    public float MyMethod()
    {
        baseFloat = 3.14f;
        
        return MyMethodOutput;
    }
}

class Child : Parent
{
    protected override float MyMethodOutput => 6.28f;
}
var child = new Child();

Console.WriteLine(child.MyMethod());

will then print 6.28.

  • Related