Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically call base method

Tags:

c#

inheritance

I need to call automatically base class method when calling overriden one (like constructors call base). For example:

class A
{
    public void Fun()
    {
        Console.Write("Class A!");
    }
}

class B : A
{
    public void Fun()
    {
        Console.Write("Class B!");
    }
}

I want to see on the screen

Class A! Class B!

when executing next code:

B b = new B();
b.Fun();

Could anyone tell me please what need to change in example code or how better to write to get required result? Thanks.

like image 659
kyrylomyr Avatar asked Nov 27 '22 08:11

kyrylomyr


1 Answers

If you don't want to call it explicitly and therefore ensure A.Fun() is called in the derived class, you could use something called the template method pattern:

class A
{
    public void Fun()
    {
        Console.Write("Class A!");
        FunProtected();
    }

    protected virtual void FunProtected()
    {
    }
}

class B : A
{
    protected override void FunProtected()
    {
        Console.Write("Class B!");
    }
}

This would give you:

new A().Fun() -> "Class A!"
new B().Fun() -> "Class A! Class B!"
like image 194
Lasse Espeholt Avatar answered Dec 06 '22 16:12

Lasse Espeholt