#715 – Private Members Are Not Visible in a Derived Class

Class members declared with an accessibility level of private are accessible only within the code for the class in which they are declared.  They are not accessible from a derived class.

In the example below, dogData is a private member of the Dog class, so it is not visible within the Terrier class (which inherits from Dog).

    public class Dog
    {
        // Stuff that's clearly public
        public string Name { get; set; }
        public int Age { get; set; }

        private int dogData;

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
            dogData = 12;
        }
    }
    public class Terrier : Dog
    {
        public Terrier(string name, int age) : base(name, age)
        {
        }

        public void Snarl()
        {
            // Compiler error: dogData is inaccessible due to its protection level
            Console.WriteLine(dogData);
        }
    }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment