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,
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,
l that are
length of the
Box class. But in the same box class I need an instance that to represent a cube, where
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
l. Thats what I have done in line 7. So just notice the syntax.
Here since we chain the constructor in the same class
keyword is being used. So how to chain the constructor in the super class,
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)
This will return a compile time (or say, typing time 😉 exception) in visual studio stating,
This is because I am using a non default constructor in the base class. Even, the below also won’t work
To overcome this defining the default constructor in the base class is always safe, as below
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.
Happy coding 🙂