#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

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: