1

Can I call a method from a grandparent class, and if so, how?

I'm trying to do something like this:

class A {
    void foo() {
        // Do something...
    }
}

class B : A {
    override void foo() {
        // Do something else...
    }
}

class C : B {
    override void foo() {
        // Call A's foo method
        // Then do something else
    }
}
CharithJ
  • 46,289
  • 20
  • 116
  • 131
PhotonChaos
  • 29
  • 1
  • 9

1 Answers1

1

One approach is to use explicit interface implementation in class A:

This allows you to call A's implementation - both from code within C and from outside C (by casting to IBob first).

using System;

namespace ConsoleApp4
{
    interface IBob
    {
        void foo();
    }

    class A : IBob
    {
        void IBob.foo()
        {
            Console.WriteLine("A");
        }

        public virtual void foo()
        {
            ((IBob)this).foo();
        }
    }

    class B : A
    {
        public override void foo()
        {
            Console.WriteLine("B");
        }
    }

    class C : B
    {
        public override void foo()
        {
            Console.WriteLine("C");

            // Writes B
            base.foo();

            // Writes A
            ((IBob)this).foo();
        }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            var sally = new C();
            sally.foo(); // A B C

            IBob sally2 = sally;
            sally2.foo(); // A

            Console.ReadLine();
        }
    }
}
mjwills
  • 23,389
  • 6
  • 40
  • 63