#798 – You Can’t Override Accessors that Are Not Accessible

When you override a virtual property in a child class, you must replicate the accessibility of the accessors in the parent’s class.

However, if one of the accessors has been made inaccessible to the child class, you’ll be able to override the property itself, but not that accessor.

In the example below, we override the Description property, including the get accessor.  However, if we try to include the set accessor in the overridden property, we get a compile-time error because the set accessor is not accessible to the child class.

    public class Animal
    {
        protected string description;
        public virtual string Description
        {
            get { return string.Format("Animal: {0}",description); }

            private set
            {
                if (value != description)
                    description = value;
            }
        }
    }
    public class Dog : Animal
    {
        public override string Description
        {
            get { return string.Format("Dog: {0}", description); }

            private set
            {
                if (value != description)
                    description = value;
            }
        }
    }

798-001

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: