#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

Advertisement