Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# call method before override method

Good day, I have a base class with a virtual method that needs to be overridden per implementation, but I would like to call the base method first before overriding. Is there a way to accomplish this without having to actually call the method.

public class Base
{
    public virtual void Method()
    {
        //doing some stuff here 
    }
}

public class Parent : Base
{
    public override void Method()
    {
        base.Method() //need to be called ALWAYS
        //then I do my thing 
    } 
}

I cannot always rely that the base.Method() will be called in the override, so I would like to enforce it somehow. This might be a design pattern of some kind, any approach to accomplish the result will do.

like image 996
Francois Taljaard Avatar asked May 23 '26 01:05

Francois Taljaard


1 Answers

One way is to define a public method in the base class, which calls another method that can be (or must be) overridden:

public class Base
{
     public void Method()
     {
        // Do some preparatory stuff here, then call a method that might be overridden
        MethodImpl()
     }

     protected virtual void MethodImpl() // Not accessible apart from child classes
     {      
     }
}

public class Parent : Base
{
    protected override void MethodImpl()
    {
       // ToDo - implement to taste
    } 
}
like image 54
Bathsheba Avatar answered May 25 '26 14:05

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!