BlackWaspTM
C# Programming
.NET 1.1+

C# Class Properties (2)

The third article in the C# Object-Oriented Programming tutorial expands upon the previous creation of simple classes by introducing properties. Properties of a class allow instantiated objects to have state with each object controlling its own data.

Using Properties

Properties of instantiated objects are accessed using the object name followed by the member access operator (.) and the property name. The property can be read from and written to using similar syntax as for a standard variable. To demonstrate this, consider the following example code, added to the Main method of the program. It creates two objects based upon the Rectangle class and assigns and reads their properties individually. When trying to assign an invalid height to a rectangle, an exception is thrown by the validation code.

static void Main(string[] args)
{
    Rectangle rect = new Rectangle();
    rect.Width = 50;
    rect.Height = 25;
    
    Rectangle square = new Rectangle();
    square.Height = square.Width = 40;
    
    Console.WriteLine(rect.Height);         // Outputs "25"
    Console.WriteLine(square.Width);        // Outputs "40"
    
    rect.Height = 125;                      // Throws the validation exception.
}

NB: The sample code demonstrates both encapsulation and state. The state of the two rectangles is held internally and independently and the implementation details of the properties are hidden from the program. If, in the future, we need to move the data from the private variables into an XML file or database, the Main method will not need to be changed.

Read-Only and Write-Only Properties

The Width and Height properties are examples of read-write properties because the information held within them can be both read and written. Sometimes you will want read-only properties or even write-only properties. These are easy to create by simply not specifying the accessors that are not required.

We can now add read-only properties for the area and perimeter of the rectangle with omitted set accessors. These properties are calculated from the existing class-level variables so require no direct internal storage. The code is as follows:

public int Area
{
    get
    {
        return _height * _width;
    }
}

public int Perimeter
{
    get
    {
        return 2 * (_height + _width);
    }
}

The new read-only properties can be read using the same syntax as the read-write properties. Test this by modifying the program's Main method:

static void Main(string[] args)
{
    Rectangle rect = new Rectangle();
    rect.Width = 8;
    rect.Height = 12;

    Console.WriteLine(rect.Area);           // Outputs "96"
    Console.WriteLine(rect.Perimeter);      // Outputs "40"
}
27 September 2007