BlackWaspTM
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");
}
30 October 2007