CSharp Polymorphism, Inheritance, Method Hiding, and Method Overriding

1 minute read,

Classes that declare virtual methods allow inheritors to permanently replace the method with their own implementation regardless of type cast.  So, if Class A defines Xoo() as virtual, then any class inheriting from A, overriding Xoo(), the inheritor’s Xoo() will be called regardless of wether the variable is treated or typecasted to A.

If you use the new keyword (Method Hiding), then whether or not the declared method is called directly depends on how a variable is being used.

For example, consider:

namespace InheritanceTest
    class A
        public virtual void Xoo(){ Console.WriteLine( "A::Xoo()" ); }
        public void Yoo(){ Console.WriteLine( "A::Yoo()" ); }
    class B : A
        public override void Xoo(){ Console.WriteLine( "B::Xoo()" ); }
        private new void Yoo(){ Console.WriteLine("B::Private Yoo()"); }
    class BB : A
        public override void Xoo(){ Console.WriteLine("BB::Xoo()"); }
        public new void Yoo(){ Console.WriteLine( "BB::Yoo()" ); }
    class C : A
        public virtual new void Xoo(){ Console.WriteLine( "C::Xoo()" ); }
        public virtual new void Yoo(){ Console.WriteLine( "C::Yoo()" ); }
    class D : C
        public override void Xoo(){ Console.WriteLine( "D::Xoo()" ); }
        public override void Yoo(){ Console.WriteLine( "D::Yoo()" ); }
    class Program
        static void Main( string[] args )
            A a = new A();
            a.Xoo();   //A::Xoo()
            a.Yoo();   //A::Yoo()

            B b = new B();
            b.Xoo();   //B::Xoo()
            b.Yoo();   //A::Yoo()<- Private 'new' B.Yoo() is
                       //           not available so A.Yoo() is called
            A ab = new B();
            ab.Xoo();  //B::Xoo()<- B.Xoo() override replaces
                       //           virtual A.Xoo() regardless of cast.
            ab.Yoo();  //A::Yoo()

            BB bb = new BB();
            bb.Xoo();  //BB::Xoo()
            bb.Yoo();  //BB::Yoo()<- If used directly as BB,
                       //            then 'new' BB.Yoo() hides A::Yoo()

            A abb = new BB();
            abb.Xoo(); //BB::Xoo()
            abb.Yoo(); //A::Yoo();<- If casted and used as A, then A::Yoo()

            C c = new C();
            c.Xoo();   //C::Xoo()
            c.Yoo();   //C::Yoo()

            A ac = new C();
            ac.Xoo();  //C::Xoo()
            ac.Yoo();  //C::Yoo()

            D d = new D();
            d.Xoo();   //D::Xoo()
            d.Yoo();   //D::Yoo()

            C cd = new D();
            cd.Xoo();  //D::Xoo()
            cd.Yoo();  //D::Yoo()

            A ad = new D();
            ad.Xoo();  //A::Xoo()
            ad.Yoo();  //A::Yoo()



Leave a comment

Your email address will not be published. Required fields are marked *