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# Constructors and Finalizers

The fourth article in the C# Object-Oriented Programming tutorial examines constructors and finalizers. These special methods allow an object to be initialised on instantiation and to perform final actions before it is removed from memory.

Constructors

In the previous article in this tutorial, we introduced properties to our class. To set these properties, an object is instantiated and the property values are assigned individually. This gives the desired result but is not ideal as it is possible for a property to be forgotten and left undefined, possibly leaving the entire object in an invalid state. This problem is solved with the use of constructors.

A constructor is a special class member that is executed when a new object is created. The constructor's job is to initialise all of the public and private state of the new object and to perform any other tasks that the programmer requires before the object is used.

In this article, we will create a new class to represent a triangular shape. This class will define three properties: the triangle's height, base-length and area. To begin, create a new console application and add a class named "Triangle". Copy and paste the following code into the class to create the three properties that are required.

public class Triangle
{
    private int _height;
    private int _baseLength;

    public int Height
    {
        get
        {
            return _height;
        }
        set
        {
            if (value < 1 || value > 100)
            {
                throw new OverflowException();
            }

            _height = value;
        }
    }

    public int BaseLength
    {
        get
        {
            return _baseLength;
        }
        set
        {
            if (value < 1 || value > 100)
            {
                throw new OverflowException();
            }

            _baseLength = value;
        }
    }

    public double Area
    {
        get
        {
            return _height * _baseLength * 0.5;
        }
    }
}

The Default Constructor

Every class includes a default constructor that is applied if no other constructor is explicitly declared by the developer. This constructor causes all of the value type properties and variables to be set to zero and all reference types to be set to null. If these are invalid values for an object, as in the Triangle class above, the default constructor will always create an object that is invalid. In this case, the default constructor should be replaced.

Replacing the Default Constructor

The syntax to add a new constructor to a class is similar to that of adding a method. However, the constructor has the same name as the class and does not include a return type. The declaration for the Triangle's new constructor is therefore simply:

public Triangle()

To ensure that all triangles will have a height and base-length within the valid range, we will make the class's constructor set both of these properties to one unit for all new Triangle objects. This is achieved by simply setting the underlying private variables in the constructor's code block. Add the following code within the class' code block to add the constructor.

public Triangle()
{
    Console.WriteLine("Triangle constructor executed");

    _height = _baseLength = 1;
}

NB: The Console.WriteLine command is added to show that the constructor has been executed in the examples. This would generally not be added to a real class definition.

Executing the Constructor

The newly added constructor replaces the default constructor and is executed automatically when a new Triangle is instantiated. This can be tested by adding some code to the console application's Main method. Add the following code and execute the program to test the results and to see that the height and base-length are set correctly.

static void Main(string[] args)
{
    Triangle triangle = new Triangle();

    Console.WriteLine("Height:\t{0}", triangle.Height);
    Console.WriteLine("Base:\t{0}", triangle.BaseLength);
    Console.WriteLine("Area:\t{0}", triangle.Area);
}

/* OUTPUT

Triangle constructor executed
Height: 1
Base:   1
Area:   0.5

*/
13 October 2007