11.5.Encapsulating Type State with Properties

The practice of accessing field data via methods was good because it supported the object-oriented concept of encapsulation. For example, if the type of m_id or m_name changed from an int type to byte, calling code would still work. Now the same thing can be accomplished in a much smoother fashion with properties, as shown in Listing 10-2.
Listing 10-2. Accessing Class Fields With Properties

using System;
publicclass Customer
{
privateint m_id = -1;

publicint ID
    {
get
        {
return m_id;
        }
set
        {
            m_id = value;
        }
    }

privatestring m_name = string.Empty;

publicstring Name
    {
get
        {
return m_name;
        }
set
        {
            m_name = value;
        }
    }
}

publicclass CustomerManagerWithProperties
{
publicstaticvoid Main()
    {
        Customer cust = new Customer();

        cust.ID = 1;
        cust.Name = "Amelio Rosales";

	Console.WriteLine(
"ID: {0}, Name: {1}",
            cust.ID,
            cust.Name);

        Console.ReadKey();
    }
}

Listing 10-2 shows how to create and use a property. The Customer class has the ID and Name property implementations. There are also private fields named m_id and m_name; which ID and Name, respectively, encapsulate. Each property has two accessors, get and set. The get accessor returns the value of a field. The set accessor sets the value of a field with the contents of value, which is the value being assigned by calling code. The value shown in the accessor is a C# reserved word.
When setting a property, just assign a value to the property as if it were a field. The CustomerManagerWithProperties class uses the ID and Name properties in the Customer class. The first line of Main instantiates a Customer object named cust. Next the value of the m_id and m_name fields of cust are set by using the ID and Name properties.
To read from a property, use the property as if it were a field. Console.WriteLine prints the value of the m_id and m_name fields of cust. It does this by calling the ID and Name properties of cust.
This was a read/write property, but you can also create read-only properties, which you’ll learn about next.

Yes No Suggest edit
Suggest Edit