#357 – Property in Derived Class Hides Base Class Property by Default

If you define a property in a derived class with the same name and type as a property in the base class, the new property hides the base class property by default.  This is true even if you don’t use the new keyword to explicitly indicate that you intend to hide the property in the base class.

If we have a Dog.Temperament property, the following two code snippets are functionally equivalent.

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

 

    public class Terrier : Dog
    {
        // No new keyword, but we're still hiding base class property
        public string Temperament
        {
            get
            {
                return string.Format("Terrier {0} is {1}", Name, temperament);
            }
        }

Without the new keyword, the compiler warns you that you’re hiding the base class property and recommends using the new keyword.

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: