1
Answer

Conundrum with Constructors.. Explain.

vernettaj

vernettaj

20y
1.9k
1
/*********************************************************** Can anybody explain why this simple program throws a System.StackOverflowException at runtime. The class has four constructors. An instance is constructed with all four constructors. A public method is then called to display each of these instances. ***********************************************************/ using System; namespace test { /// /// Summary description for Class1. /// using System; public class Test { private int x; private int y; private string instance_name; public Test() { Console.WriteLine("{0}:CTOR0",this.instance_name); this.x=0; this.y=0; this.instance_name="Anonymous"; } public Test(int x, int y):this("None") { Console.WriteLine("{0}:CTOR2",this.instance_name); } public Test(string instance_name):this(1,1) { this.instance_name = instance_name; } public Test(int x, int y,string instance_name) { Console.WriteLine("{0}:CTOR1",this.instance_name); this.x=x; this.y=y; this.instance_name = instance_name; } ~Test() { Console.WriteLine("{0}:DTOR0",this.instance_name); } public void Dump() { Console.WriteLine("{0}:({1},{2})",this.instance_name,this.x,this.y); } public static void Main() { Test t1 = new Test(); Test t2 = new Test(10,10,"TopLeft"); Test t3 = new Test(11,11); Test t4 = new Test("Ambiguous"); t1.Dump(); t2.Dump(); t3.Dump(); t4.Dump(); } } }

Answers (1)