this and base?using System; class BaseClass { public BaseClass() { Console.WriteLine("BaseClass default constructor"); } public BaseClass(string msg) { Console.WriteLine("BaseClass says: " + msg); } } class DerivedClass : BaseClass { public DerivedClass() : this("Hello") { Console.WriteLine("DerivedClass default constructor"); } public DerivedClass(string msg) : base(msg) { Console.WriteLine("DerivedClass says: " + msg); } } class Program { static void Main() { var obj = new DerivedClass(); } }
this calls another constructor in the same class before executing the body, and base calls the base class constructor.The DerivedClass() constructor calls this("Hello"), which calls DerivedClass(string msg). That constructor calls base(msg), which prints "BaseClass says: Hello". Then it prints "DerivedClass says: Hello". After returning, the DerivedClass() constructor prints "DerivedClass default constructor".
using System; class A { public A() { Console.WriteLine("A()"); } public A(int x) { Console.WriteLine("A(int)"); } } class B : A { public B() : base(5) { Console.WriteLine("B()"); } public B(int x) : this() { Console.WriteLine("B(int)"); } } class Program { static void Main() { var b = new B(10); } }
The B(int x) constructor calls this(), so B() runs first. B() calls base(5), so A(int) runs first. Then B() prints, then B(int) prints.
class Test { public Test() : this(5) { } public Test(int x) : this() { } }
The Test() constructor calls this(5), and Test(int x) calls this(). This creates an infinite loop of constructor calls, which is detected at compile time as a cycle.
using System; class X { public X() { Console.WriteLine("X()"); } public X(string s) : this() { Console.WriteLine("X(string): " + s); } } class Y : X { public Y() : base("hello") { Console.WriteLine("Y()"); } public Y(int n) : this() { Console.WriteLine("Y(int): " + n); } } class Program { static void Main() { var y = new Y(10); } }
Y(int) down to base.Y(int) calls this(), so Y() runs first. Y() calls base("hello"), so X(string) runs, which calls X() first. So order is X(), X(string), Y(), Y(int).
Constructor chaining lets one constructor call another, so common initialization code is written once and reused. This reduces duplication and errors.