this() call
Learn to chain to another constructor with this().
Chaining with this()
A constructor can call another constructor in the same class using the this(...) syntax. This is called constructor chaining. It avoids duplication: shared code lives in one constructor.
Example: public Point() : this(0, 0) { }. When the parameterless constructor is called, it first runs the two-parameter constructor Point(0, 0). The this(0, 0) expression is written after a colon, before the body.
Why use this()?
If each overloaded constructor repeats the same assignments, maintenance becomes hard. With this() you delegate to the most general constructor, so shared code lives in one place. When you add a new field, you update only that constructor.
The execution order is: first the constructor pointed to by this(...) runs completely, then the body of the calling constructor runs. This way the base assignments are always done first.
Exercise Chain constructors with this() in Point
Add public int X { get; set; } and public int Y { get; set; } properties to the Point class. Declare two constructors: first public Point(int x, int y) with X = x; Y = y; in the body. Second public Point() : this(0, 0) { } chaining to the first. Inside Main create an instance with new Point() and print X.
Show example solution
this(0, 0). In Main write Point p = new Point(); Console.WriteLine(p.X);
Example solution:
using System;
class Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public Point() : this(0, 0)
{
}
}
class Program
{
static void Main()
{
Point p = new Point();
Console.WriteLine(p.X);
}
}
Test yourself
-
What does this(0, 0) do?
public Point() : this(0, 0) { }- Assigns a static field
- Calls a method
- Starts a loop
- Calls another constructor
Show answer
Calls another constructor — Correct. this(0, 0) delegates to the two-parameter constructor.
-
Complete the this() call
public Point() : ____(0, 0) { }Show answer
public Point() : this(0, 0) { } -
Match each this() part to its role
- : this(0, 0)
- Chains to same-class ctor
- public Point()
- The calling constructor
- this
- The current class
- (0, 0)
- The arguments passed