#723 – New Methods in Subclass May Not Be Visible in Derived Classes

You can use the new keyword in a subclass to hide a method in the parent class.  The new implementation of the method will now be used in the context of the subclass.

If you call this method in a subclass of the subclass, however, the method called depends on the accessibility of the new method.  If the new method is private, it is not visible in the lowest level class and so the original member in the base class is called.

    public class Dog
    {
        public void Bark()
        {
            Console.WriteLine("Dog: Woof");
        }
    }

    public class Terrier : Dog
    {
        public void DoBark()
        {
            Bark();
        }

        private new void Bark()
        {
            Console.WriteLine("Terrier: Woof");
        }
    }

    public class Yorkshire : Terrier
    {
        public void DoBark()
        {
            // Dog.Bark is called
            Bark();
        }
    }

 

            Dog d = new Dog();
            d.Bark();

            Terrier t = new Terrier();
            t.DoBark();

            Yorkshire y = new Yorkshire();
            y.DoBark();