BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Class Properties

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"
}

Using the Property Internally

In the Rectangle example, the area and perimeter properties are calculated using the class-level variables that hold the actual values. This is not always possible, or indeed advisable, particularly if a property involves a calculation or validation process. Rather than duplicating the code for the calculation or validation, the property can be accessed by name. We could, therefore, adjust the Area property as follows:

public int Area
{
    get
    {
        return Height * Width;
    }
}

With this updated version of the Area property, the source of the height and width values has been disassociated from the internal variables. If the Height and Width properties are changed in the future to retrieve their values from a database, no changes to the Area property will be required.

The "this" Keyword

A final keyword to consider is "this". The "this" keyword can be used within a class's code to refer to the current instantiated object. For properties this is rarely required unless poor naming of variables has led to a property name being hidden. In the following example, the method compares the area of the current object to an area value passed as a parameter. To access the property name, the "this" keyword is used because the method's parameter has been badly named and thus hides the property:

public bool AreaTheSame(int area)
{
    if (this.Area == area)
    {
        return true;
    }
    else
    {
        return false;
    }
}

NB: It would be more appropriate to rename the method's parameter in the above situation.

The "this" keyword does have another use. If a method is being called and the current object is to be passed to that method, setting a parameter to "this" achieves the desired result. For example:

floorShape.Set(this);
27 September 2007