#242 – Declaring and Using a Property in a Class

You can create instance data in a class by defining public fields.  You can read and write fields using a reference to an instance of the class.

A class more often exposes its instance data using properties, rather than fields.  A property looks like a field from outside the class–it allows you to read and write a value using a reference to the object.  But internally in the class, a property just wraps a private field, which is not visible from outside the class.

    public class Dog
    {
        // Private field, stores the dog's name
        private string name;

        // Public property, provides a way to access
        // the dog's name from outside the class
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

    }

Using the property:

            Dog kirby = new Dog();

            kirby.Name = "Kirby";
Advertisements

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

One Response to #242 – Declaring and Using a Property in a Class

  1. Pingback: #791 – Properties Are Not Variables | 2,000 Things You Should Know About C#

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 )

Google+ photo

You are commenting using your Google+ 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: