A day with .Net

My day to day experince in .net

Archive for April, 2015

Why you need to opt for Constructor Chaining

Posted by vivekcek on April 5, 2015

The simple way to answer this question is, Constructor chaining avoid duplication of IL code or reduce the size of IL code.

Please look at the below example

class MyClass
 {
 int a = 10;
 int b = 5;
 string c = "vivek";
 int d;

 public MyClass()
 {
 c = "change";
 }

 public MyClass(int _a)
 {
 a = _a;
 }

 public MyClass(string _c)
 {
 c = _c;
 }
 }

Now inspect the above class’s IL code.

You can found that the inline initialization of varibles are moved inside the constructor by compiler.
This is the way constructor initialization is working in c#.
Look at the IL code of parameterless constructor.

Which include code to initialize a, b, c. But the code to initialize ‘d’ is missing. CLR will initialize d to default value.
After the initialization of a,b,c there is code to change the value of c.

Nochainparameterless

Look at the IL code of constructor that take int parameter.
The same code to initialize a, b, c is there.
At the end there is code to change the value of a.

NoChainInt32

Look at the IL code of constructor that take string parameter.
The same code to initialize a, b, c is there.
At the end there is code to change the value of c.

NoChainString

So code duplication is found in all constructors
Now we will modify our code with constructor chaining syntax and find the difference.

class chain
 {
 int a;
 int b;
 string c;
 int d;

 public chain()
 {
 int a = 10;
 int b = 5;
 string c = "vivek";
 }

 public chain(int _a)
 : base()
 {
 a = _a;
 }

 public chain(string _c)
 : base()
 {
 c = _c;
 }
 }

Look at the IL code of parameterless constructor.
Which include code to initialize a, b, c
Chainparameterless
Look at the IL code of constructor that take int parameter.
Woww there is no code to initialize a,b,c.
Only the code to change the value of a is there

ChainInt

Look at the IL code of constructor that take string parameter.
Woww there is no code to initialize a,b,c.
Only the code to change the value of c is there.

Chainstring

So the conclusion is, use constructor chaining.

Advertisements

Posted in Uncategorized | Leave a Comment »