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# Constructor Overloading

The seventh article in the C# Object-Oriented Programming tutorial extends the previous description of method overloading with constructor overloading. Using this technique, multiple constructors can be created to choose from during object instantiation.

Constructor Overloading

Earlier in this tutorial we considered the use of constructors and of method overloading. In this article we will combine these two techniques to allow a number of constructors to be defined for a single class. This gives the class the flexibility to construct objects in a variety of ways according to the manner in which they are to be used.

Creating Overloaded Constructors

Creating an overloaded constructor is as simple as adding overloaded methods. The additional constructors are simply added to the code. Each constructor must have a unique signature, ie. the parameter types must differ from all other constructors.

To demonstrate the use of overloaded constructors we will create a new class to represent rectangular shapes. The class will allow the generation of a Rectangle object with specified Height and Width properties. We will then add a second constructor that requires only a single parameter for square shapes with matching height and width.

To begin, create a new console application and add a new class file named "Rectangle". Add the following code to the new class to create the properties:

class Rectangle
{
    private int _height;
    private int _width;

    public int Height
    {
        get { return _height; }
    }

    public int Width
    {
        get { return _width; }
    }
}

NB: In this code, the Height and Width properties have been made read-only. This is to simplify the code in this article.

Adding the Constructors

We can now add the first constructor to the class. This constructor accepts two parameters containing the height and width of the rectangle. Validation code ensures that they are both positive values before storing them in the property variables. By adding this constructor, the default constructor will be removed. Add the following constructor to the class:

public Rectangle(int height, int width)
{
    if (height <= 0) throw new ArgumentException("height");
    if (width <= 0) throw new ArgumentException("width");

    _height = height;
    _width = width;

    Console.WriteLine("Rectangle Constructor Called");
}

To add a second constructor, we simply declare another variation with a different signature. Add the following code that permits the creation of Rectangle objects that represent squares. It requires only a single parameter that can be stored in both the width and height property variables.

public Rectangle(int size)
{
    if (size <= 0) throw new ArgumentException("height");

    _height = _width = size;

    Console.WriteLine("Square Constructor Called");
}

Using Overloaded Constructors

Overloaded constructors can be used to instantiate objects in exactly the same manner as for classes with a single constructor. During compilation of the code, the compiler compares the signature used for the new object to those available in the class. If there is a perfect match, the corresponding constructor is used. Where there is no signature with the correct parameters, the compiler will look for a constructor that can be used with implicit casting. If no such constructor exists, a compiler error occurs.

We can now test the example code by modifying the program's main method as follows:

static void Main(string[] args)
{
    Rectangle rect = new Rectangle(4, 6);
    Console.WriteLine("Height: {0}", rect.Height);
    Console.WriteLine("Width: {0}", rect.Width);

    Rectangle square = new Rectangle(5);
    Console.WriteLine("Height: {0}", square.Height);
    Console.WriteLine("Width: {0}", square.Width);
}

/* OUTPUT

Rectangle Constructor Called
Height: 4
Width: 6
Square Constructor Called
Height: 5
Width: 5

*/

Constructor Interaction

Constructors can be very complex, performing many initialisation and validation functions for new objects. This can easily lead to large constructors with functionality that is repeated in each overloaded version. This, in turn, can lead to maintenance problems with the code when changes to construction logic are required. This can be minimised by having the constructor call methods within the class to perform common tasks. Another option is to allow code reuse by having the constructors call each other during object instantiation.

Constructor Calling Syntax

To create a constructor that calls an existing constructor, a special syntax is used. The constructor is declared as usual and then a colon character (:) is appended. After the colon the this keyword and the parameter list of the called constructor is provided. Each parameter specified in the call must match one of those in the new constructor or be a literal value.

public Constructor(parameters-1) : this(parameters-2) { }

When the new constructor is utilised, the constructor indicated in the this command is executed first, then the code within the new constructor's code block is run. It is possible that the code block is empty where only a transformation of signature is required. In this case, only the original constructor is executed with the specified parameters.

This reuse of code can be demonstrated by modifying the constructor that creates a square Rectangle object as follows:

public Rectangle(int size) : this(size, size)
{
    Console.WriteLine("Square Constructor Called");
}

Running the program now shows the order of execution of constructors. The results are as follows:

Rectangle Constructor Called
Height: 4
Width: 6
Rectangle Constructor Called
Square Constructor Called
Height: 5
Width: 5
30 October 2007