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

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.

One Response to #240 – Private and Public Instance Data in a Class

  1. Pingback: Tweets that mention #240 – Private and Public Instance Data in a Class « 2,000 Things You Should Know About C# -- Topsy.com

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers