When overloading constructor in C# I always tends to forgot what is the execution cycle during runtime. So I made a quick program with LinqPad to refresh my mind.
1st I create a simple class Item with multiple constructor overloading each others.
then I create a Main function to create new Item.
When the program runs it will produce the following output:
Seeing the output quickly understand how the flow of execution.
1st I create a simple class Item with multiple constructor overloading each others.
class Item {
private int i = 1;
public Item(){
this.i = i*10;
Console.WriteLine("Item - constructor 1 executed. i = "+ this.i);
}
public Item(int i) : this(){
this.i *= i;
Console.WriteLine("Item - constructor 2 executed. i = "+ this.i);
}
public Item(string a) : this(5){
Console.WriteLine("Item - constructor 3 executed. i = "+ this.i);
}
}
then I create a Main function to create new Item.
// Constructor Overloading
void Main()
{
Console.WriteLine("START");
Console.WriteLine("--------------");
var i = new Item();
Console.WriteLine("--------------");
var i2 = new Item(2);
Console.WriteLine("--------------");
var i3 = new Item("Hello");
Console.WriteLine("--------------");
Console.WriteLine("END");
}
When the program runs it will produce the following output:
START
--------------
Item - constructor 1 executed. i = 10
--------------
Item - constructor 1 executed. i = 10
Item - constructor 2 executed. i = 20
--------------
Item - constructor 1 executed. i = 10
Item - constructor 2 executed. i = 50
Item - constructor 3 executed. i = 50
--------------
END
Seeing the output quickly understand how the flow of execution.
Comments
Post a Comment