#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

#797 – Setting Accessibility for Property Accessors

By default, the accessibility of a property accessor matches the accessibility of the property itself.  You can also explicitly set the accessibility of an accessor, within certain limitations.

When setting the accessibility of a property accessor:

  • You can’t make an accessor more accessible than the property itself
  • You can’t specify the exact same accessibility on the accessor as the property
  • The property must have both get and set accessors defined
  • You can only set accessibility on one of the accessors, not both
  • You can’t set the accessibility of an accessor on a property in an interface
  • When overriding a virtual property in a parent class, you must replicate the accessibility of the accessors in the parent’s class exactly

The bottom line–you can make one of the accessors a bit more restrictive than the other.

        public string Name { get; protected set; }