Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Constructor Overloading in C# (OOP’s) – Part 15

Posted by Ravi Varma Thumati on July 13, 2009

C# Constructor Overloading

In this article we will combine constructor and overloading 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;

}

}

}

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.

Advertisements

4 Responses to “Constructor Overloading in C# (OOP’s) – Part 15”

  1. Roy Laulu said

    I couldn’t currently have asked for a much better blog. You’re there to supply excellent guidance, going instantly to the point for easy understanding of your site visitors. You’re undeniably a terrific professional in this subject. Thanks a lot for remaining there for people like me.

  2. Actually like your websites particulars! Undoubtedly an exquisite provide of knowledge that is extremely helpful. Keep it up to hold publishing and that i’m gonna proceed reading by way of! Cheers.

  3. net rocket said

    Thanks for taking the time to talk about this, I feel strongly about it and enjoy understanding more on this subject. If feasible, as you gain expertise, would you thoughts updating your weblog with far more facts? It’s extremely useful for me.

  4. Good job right here. I truly enjoyed what you had to say. Keep heading because you surely bring a new voice to this subject. Not many people would say what youve said and still make it interesting. Nicely, at least Im interested. Cant wait to see additional of this from you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: