Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force method to call base method from base class

Tags:

c#

oop

If i am creating method with "override" property, derived method will not call base method implementation automatically and i will need to call it manually using "base" keyword like this:

public class A
{
    public virtual void Say()
    {
        Console.Write("A");
    }
}

public class B : A
{
    public override void Say()
    {
        base.Say();
        Console.Write("B");
    }
}

So only in this case string "A" and "B" will be written to console. So the question is how can i get rid of "base.Say();" line? So i want to force every derived method "Say" to call base method from base class. Is it possible? I am looking for any solutions, even if i will be forced to use other keywords

like image 777
Eugen1344 Avatar asked Oct 19 '25 22:10

Eugen1344


1 Answers

Although it is not possible to achieve this directly, you could get the same effect by writing your own method that is not virtual, which calls the virtual after performing some fixed operation:

public class A
{
    public void Say()
    {
        Console.Write("A");
        SayImpl();
    }
    protected virtual void SayImpl()
    {
        // Do not write anything here:
        // for the base class the writing is done in Say()
    }
}

public class B : A
{
    protected override void SayImpl()
    {
        Console.Write("B");
    }
}

Now any class inheriting from A and implementing SayImpl() would have A prepended to its printout.

like image 151
Sergey Kalinichenko Avatar answered Oct 22 '25 13:10

Sergey Kalinichenko



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!