Search code examples
c#.netinheritancepartial-classes

Partial classes/partial methods vs base/inherited classes


a question about class design. Currently I have the following structure:

abstract Base Repository Class

Default Repository implementation class (implements some abstract methods, where logic is common thru all of the Specific classes but leaves other empty)

Specific Repository implementation Class (implements what is left empty in the above Default class)

I've now came to the problem where I have a specific Update() method in Specific class but when all the code in this method executes some code from the base Default class should be executed too.

I could do it like this

public override Update()
{
    // do Specific class actions and updates
    // ....

    // follow with base.Update()
    base.Update();
}

but this requires those base.XYZ() calls in all the inherited methods. Could I go around that somehow with partials?

So the requirement is to have code in both parent and inherited class (or to make those two one class using partials) and code from method implementation in both places should be executed. Also what about if I wanted to turn it around and execute base class code first followed by the inherited class code?

thanks


Solution

  • Have you considered something like:

    public abstract class YourBaseClass
    {
        public void Update()
        {
            // Do some stuff
            //
    
            // Invoke inherited class's  method
            UpdateCore();
        }
    
        protected abstract void UpdateCore();
    }
    
    public class YourChildClass : YourBaseClass
    {
         protected override void UpdateCore()
         {
             //Do the important stuff
         }
    }
    
    
    //Somewhere else in code:
    var ycc = new YourChildClass();
    ycc.Update();