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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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:


1
2
3
Dog kirby = new Dog();
 
kirby.Name = "Kirby";