#309 – Accessing Protected Members In a Derived Class

A member of a class with its accessibility set to protected is accessible from within the class that defines the member and from within classes that derive from the defining class.

You’d typically access protected instance members through the this reference in the defined class.

    public class Dog
    {
        protected string locationOfBone;
    }

    public class Terrier : Dog
    {
        public void DivulgeTerrierSecrets()
        {
            // CAN access protected member through implicit this reference
            Console.WriteLine("Bone is: {0}", locationOfBone);
        }
    }

However, when the subclass is accessing the protected member, it must do so through an instance of the subclass and not through an instance of the parent class.

    public class Terrier : Dog
    {
        public static FindSecret()
        {
            Terrier t = new Terrier("Jack");
            string s = t.locationOfBone;   // OK

            Dog d = new Dog("Spot");
            string s = d.locationOfBone;   // Not OK - ERROR
        }
    }
Advertisements