Search code examples
c#inheritancepolymorphismoverridingvirtual-functions

C#: Any way to skip over one of the base calls in polymorphism?


class GrandParent
{
    public virtual void Foo() { ... }
}

class Parent : GrandParent
{
    public override void Foo()
    {
       base.Foo();

       //Do additional work
    }
}

class Child : Parent
{
    public override void Foo()
    {
        //How to skip Parent.Foo and just get to the GrandParent.Foo base?

        //Do additional work
    }
}

As the code above shows, how can I have the Child.Foo() make a call into GrandParent.Foo() instead of going into Parent.Foo()? base.Foo() takes me to the Parent class first.


Solution

  • Your design is wrong if you need this.
    Instead, put the per-class logic in DoFoo and don't call base.DoFoo when you don't need to.

    class GrandParent
    {
        public void Foo()
        {
            // base logic that should always run here:
            // ...
    
            this.DoFoo(); // call derived logic
        }
    
        protected virtual void DoFoo() { }
    }
    
    class Parent : GrandParent
    {
        protected override void DoFoo()
        {    
           // Do additional work (no need to call base.DoFoo)
        }
    }
    
    class Child : Parent
    {
        protected override void DoFoo()
        {  
            // Do additional work (no need to call base.DoFoo)
        }
    }