#355 – Use the new Keyword to Replace a Property in a Base Class

A derived class inherits data and behavior from its parent class.

There are times when you might want to replace property accessors in a base class with new accessors in the derived class, using the same property name.  You can do this using the new keyword.

Assume a Dog class has a Temperament property:

        protected string temperament;
        public string Temperament
        {
            get
            {
                return string.Format("{0} is {1}", Name, temperament);
            }

            set
            {
                temperament = value.ToLower();
            }
        }

You can provide a new version of this property in a class that derives from Dog, using the new keyword.  This new property hides the property in the base class.

        public new string Temperament
        {
            get
            {
                return string.Format("Terrier {0} is {1}", Name, temperament);
            }

            set
            {
                temperament = value.ToUpper();
            }
        }

The get/set accessors used will now depend on the type of the object.

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

One Response to #355 – Use the new Keyword to Replace a Property in a Base Class

  1. Pingback: #356 – Hidden Base Class Property Is Used Based on Declared Type of Object « 2,000 Things You Should Know About C#

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: