#716 – How Derived Classes Can Access Protected Members

Marking a class member as protected indicates that the member can be used from code within that class or from code in a derived class.

The derived class, however, can only access a protected member through an instance of the derived class or one of its own subclasses.

In the example below, SecretName is defined in Dog as protected.  It can be accessed in the Terrier subclass only through a Terrier instance, not a Dog instance.

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

        public Dog(string name, string secretName)
        {
            Name = name;
            SecretName = secretName;
        }
    }

    public class Terrier : Dog
    {
        public Terrier(string name, string secretName) : base(name, secretName)
        {
        }

        public void GatherIntel(Dog d, Terrier t)
        {
            // Ok
            Console.WriteLine(string.Format("Dog:{0}, Terrier:{1}", d.Name, t.Name));

            // Ok
            Console.WriteLine(string.Format("Me:{0}, Him:{1}", this.SecretName, t.SecretName));

            // Compiler error
            Console.WriteLine(string.Format("Dog is {0}", d.SecretName));
        }
    }
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: