#684 – Hidden Base Class Members Aren’t Really Hidden

When authoring a derived class, you can hide a member of the base class using the new keyword.  For a method, this indicates that the method in your derived class replaces the method in the base class and will be called when invoked on objects of the derived type.  (It also means that the method will not behave polymorphically).

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

    public class Terrier : Dog
    {
        public new void Bark()
        {
            Console.WriteLine("Terrier: Yip yip");
        }
    }

However, if you have an instance of the derived class and cast it to the type of its base class, you’ll end up accessing the method in the base class after all.

            Terrier t = new Terrier();

            t.Bark();         // Yip yip

            ((Dog)t).Bark();  // Woof
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: