11.3.Creating a Write-Only Property

You can assign values to, but not read from, a write-only property. A write-only property only has a set accessor. Listing 10-4 shows you how to create and use write-only properties.
Listing 10-4. Write-Only Properties

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

publicint ID
    {
set
        {
            m_id = value;
        }
    }

privatestring m_name = string.Empty;

publicstring Name
    {
set
        {
            m_name = value;
        }
    }

publicvoid DisplayCustomerData()
    {
        Console.WriteLine("ID: {0}, Name:
            {1}", m_id, m_name);
    }
}

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

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

        cust.DisplayCustomerData();

        Console.ReadKey();
    }
}

This time, the get accessor is removed from the ID and Name properties of the Customer class, shown in Listing 10-1. The set accessors have been added, assigning value to the backing store fields, m_id and m_name.
The Main method of the WriteOnlyCustomerManager class instantiates the Customer class with a default constructor. Then it uses the ID and Name properties of cust to set the m_id and m_name fields of cust to 1 and “Amelio Rosales”, respectively. This invokes the set accessor of ID and Name properties from the cust instance.
When you have a lot of properties in a class or struct, there can also be a lot of code associated with those properties. In the next section, you’ll see how to write properties with less code.

Yes No Suggest edit
Suggest Edit