Constructor chaining and some other good tips with constructors

Blogging after a long time actually, I was bit busy with last exams and migrating to Colombo, Sri Lanka. I have a good news for you guys that I have joined IFS, Sri Lanka as an undergraduate intern that valid from 11th March to 19th June. Here, at IFS, this has a tremendous work place setup and the people as well. Wow thats amazing and I praise god for writing my fate to be here 🙂

So today I have learnt something special, which I didn’t really used even I didn’t read in any books I used for reading on C#. That is CONSTRUCTOR CHAINING.

In simple words, Constructor chaining is calling a constructor from another constructor. The called constructor may reside in the same class of the caller constructor risiding constructor or its super class(In C# we call it as base class). The main advantages of this is we are avoiding boilerplate code as we don’t have to repeat the same operations and even this can be used, if all fields of the class to be initialized.

Lets see a small code for this,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Box
{
    int length; // fields
    int width;
    int height;

    public Box(int len)
        : this(len, len, len)
    { // constructor with one parameter

    }

    public Box(int h, int w, int l)
    { // constructor with three  parameter
        length = l;
        width = w;
        height = h;
    }
}

Here for the Box class I have two overloaded constructors with different signatures, that are Box(int len) in line 7 and public Box(int h, int w, int l) in line 13. First lets have a look at the constructor in line 13, that initialize a box object with three user defined parameters, h, w and l that are height, width and length of the Box class. But in the same box class I need an instance that to represent a cube, where w, h and l are the eual values, so instead of writing another logic for that I can simply create another constructor that calls the constructor in line 13 and put single value to all the variables h and l. Thats what I have done in line 7. So just notice the syntax.

public Box(int len)
        : this(len, len, len)
    { // constructor with one parameter

    }

Here since we chain the constructor in the same class this keyword is being used. So how to chain the constructor in the super class,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Cube:Box
{
    int length;
    public Cube(int l):base(l,l,l)
    {
        this.length = l;
    }

}

class Box
{
    int height, width, length;
    public Box(int h, int w, int l)
    {
        this.height = h;
        this.width = w;
        this.length = l;
    }

    internal int getVolume()
    {
        return height * width * length;
    }
}

See line 4 where I have did something public Cube(int l):base(l,l,l) in this line and this is where I chain the constructor from the base class.

Now in the Box if I try to add another constructor (say I am adding the missing default constructor)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Cube:Box
{
    int length;
    public Cube(int l):base(l,l,l)
    {
        this.length = l;
    }

    public Cube()
    { }

}

This will return a compile time (or say, typing time 😉 exception) in visual studio stating,

Error 1 'OOPIntro_D103.Box' does not contain a constructor that takes 0 arguments 

This is because I am using a non default constructor in the base class. Even, the below also won’t work

class Cube:Box
{
    int length;
    //public Cube(int l):base(l,l,l)
    //{
    //    this.length = l;
    //}

    public Cube()
    { }

}

To overcome this defining the default constructor in the base class is always safe, as below

public Box() {}

So remember to create constructors for the base classes whatever we needed in the child class. And stating default constructor gives the freedom to create any kind of constructor in the child class.
Final example,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Program
{
    static void Main(string[] args)
    {
        Cube c = new Cube(5);
        Console.WriteLine(c.getVolume());
        Console.ReadKey();
    }
}

class Cube : Box
{
    int length;
    public Cube(int l)
        : base(l, l, l)
    {
        this.length = l;
    }

    public Cube(string y)
    { }

}

class Box
{
    int height, width, length;
    public Box() { }
    public Box(int h, int w, int l)
    {
        this.height = h;
        this.width = w;
        this.length = l;
    }

    internal int getVolume()
    {
        return height * width * length;
    }
}

Happy coding 🙂

Advertisements

One thought on “Constructor chaining and some other good tips with constructors

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