11.4.Creating Read-Only Properties

Properties can be made read-only. This is accomplished by having only a get accessor in the property implementation. Listing 10-3 demonstrates how you can create a read-only property.
Listing 10-3. Read-Only Properties

using System;
publicclass Customer
{
privateint m_id = -1;
privatestring m_name = string.Empty;

public Customer(int id, string name)
    {
        m_id = id;
        m_name = name;
    }

publicint ID
    {
get
        {
return m_id;
        }
    }

publicstring Name
    {
get
        {
return m_name;
        }
    }
}

publicclass ReadOnlyCustomerManager
{
publicstaticvoid Main()
    {
        Customer cust = new Customer(1, "Amelio Rosales");

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

        Console.ReadKey();
    }
}

The Customer class in Listing 10-3 has two read-only properties, ID and Name. You can tell that each property is read-only because they only have get accessors. At some time, values for the m_id and m_name must be assigned, which is the role of the constructor in this example.
The Main method of the ReadOnlyCustomerManager class instantiates a new Customer object named cust. The instantiation of cust uses the constructor of Customer class, which takes int and string type parameters. In this case, the values are 1 and “Amelio Rosales”. This initializes the m_id and m_name fields of cust.
Since the ID and Name properties of the Customer class are read-only, there is no other way to set the value of the m_id and m_name fields. If you inserted cust.ID = 7 into the listing, the program would not compile, because ID is read-only; the same goes for Name. When the ID and Name properties are used in Console.WriteLine, they work fine. This is because these are read operations which only invoke the get accessor of the ID and Name properties.
One question you might have now is “If a property can be read-only, can it also be write-only?” The answer is yes, and explained in the next section.

Yes No Suggest edit
Suggest Edit