#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));
        }
    }