#240 – Private and Public Instance Data in a Class

In a class, you can define public instance data, as fields.  Any instance of the class can read and write the instance data stored in these fields.

For example:

    public class Dog
    {
        public string Name;
        public int Age;
    }

    // Creating a Dog object
    Dog kirby = new Dog();
    kirby.Name = "Kirby";
    kirby.Age = 14;

You might, however, want to declare some instance data that is visible from within the class’ methods, but not visible outside the class.  You can do this by declaring a field as private.

        public string Name;
        public int Age;

        private DateTime lastPrint;

        public void PrintName()
        {
            Console.WriteLine(Name);

            // lastPrint is visible here
            lastPrint = DateTime.Now;
        }

This private field will not be visible from outside the class.

            Dog kirby = new Dog();
            kirby.Name = "Kirby";

            // Compiler error: inaccessible due to its protection level
            DateTime when = kirby.lastPrint;
Advertisement