#717 – Class Members Can’t Be More Accessible Than Their Type

When specifying the accessibility for a class member, the member’s type must be at least as accessible as the member itself.  For methods, the return type and types of all parameters must be as accessible as the method.

This makes sense–client code can’t access a class member if it can’t access that member’s type.  Client code also can’t invoke a method if it can’t access the type of all the method’s parameters and return type.

In the example below, because the DogCollar type is internal, the Collar property must be internal or private.

    internal class DogCollar
    {
        public string Material { get; set; }
        public double Size { get; set; }
    }

    public class Dog
    {
        public string Name { get; set; }

        // Error: DogCollar less accessible (internal) than Collar (public)
        public DogCollar Collar { get; set; }

        public Dog(string name)
        {
            Name = name;
        }
    }
Advertisements