#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();
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: