BlackWaspTM
C# Programming
.NET 1.1+

C# Constructors and Destructors

The fourth article in the C# Object-Oriented Programming tutorial examines constructors and destructors. 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.

13 October 2007