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

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

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 )

Connecting to %s

%d bloggers like this: