BlackWaspTM
C# Programming
.NET 1.1+

C# Structures (2)

The twenty-second, and final, part of the C# Object-Oriented Programming tutorial reviews the use of structures. Structures provide similar functionality to classes, but when instantiated resultant variables are value types, rather than reference types.

Creating a Structure

To demonstrate the use of structures, we will create one that represents a vector. This simple structure will include X and Y properties and a method that calculates the length of the vector. To begin, create a new console application named "CSharpStructures" and add a new class file named "Vector" to the project.

Syntax

The syntax for declaring a structure is similar to that of a class. However, instead of using the class keyword, the structure name is prefixed with "struct". The general syntax for a simple structure is therefore:

struct structure-name {}

As described above, structures may implement one or more interfaces. If required, the interface names are appended to the declaration as a comma-separated list. The first interface's name is prefixed with a colon character (:).

struct structure-name : interface-1, interface-2, ..., interface-x {}

Depending upon the development environment that you prefer, the generated Vector code file may include a class definition. If it does, remove it. Add the new structure definition to the code file as follows:

struct Vector
{
}

Adding Properties

The new structure requires properties to hold the X and Y co-ordinates. These will contain integer values. The syntax for creating a property is identical to that of creating a class property. However, if linking the property to a private field, as shown below, the field may not be initialised in its declaration.

To create the two properties, add the following code within the structure's code block:

private int _x, _y;

public int X
{
    get { return _x; }
    set { _x = value; }
}

public int Y
{
    get { return _y; }
    set { _y = value; }
}

Adding a Method

We can now add a method to the structure that calculates the length of the vector using the Pythagorean Theorem and the values of the two co-ordinates. To define this method, add the following code:

public double CalculateLength()
{
    return Math.Sqrt(_x * _x + _y * _y);
}
5 May 2008