alan2here
alan2here

Reputation: 3327

c# inheritance general then specific

class base_c
{
    public virtual void a() {}
    public virtual void b() {}
    public virtual void c() {}
    public virtual void d() {}
}

class other_c : base_c
{
    public void a() {}
    public new void b() {}
    public override void c() {}
    public override void d() {base.d();}
}

class Program
{
    static void Main()
    {
        base_c game2 = new other_c();
        game2.a();
        game2.b();
        game2.c();
        game2.d();
    }
}

'd' has the desired behaviour that the more general base_c function occurs as well as the more specific other_c, although it would nice if the order was the other way round. To see this in effect, use the debugger and step though the program.

Is 'd' the best way to achieve this result?

Although it could be changed in this example "base_c game2 = ..." must remain base_c and cannot be changed to other_c.

Upvotes: 0

Views: 91

Answers (1)

dthorpe
dthorpe

Reputation: 36092

Yes, if your intent is for the child class to extend the inherited behavior in method D, then the pattern is to call base.d() in the child's override of d.

If your intent is to replace the inherited behavior (not extend), then you would not call the base method.

You also have the choice of whether to call the base method first before doing anything in your overriding method, or call the base in the middle or after your code in your overriding method.

All of these are valid techniques in the appropriate situations.

Upvotes: 6

Related Questions