I have this piece of code :
public class Time2
{
private int hour;
private int minute;
private int second;
public Time2(int h = 0, int m = 0, int s = 0)
{
SetTime(h, m, s);
}
public Time2(Time2 time)
: this(time.hour, time.Minute, time.Second) { }
public void SetTime(int h, int m, int s)
{
Hour = h;
Minute = m;
Second = s;
}
I understood everything except this part:
public Time2(Time2 time)
: this(time.hour, time.Minute, time.Second) { }
Can you tell me how this constructor works? The style and the job of the "this" keyword looks very unfamiliar to me. Thanks.
the this is calling another constructor on the class before executing the code of it's own function.
Try this: and look at the output in the console.
public Time2(int h = 0, int m = 0, int s = 0)
{
Console.Log("this constructor is called");
SetTime(h, m, s);
}
public Time2(Time2 time)
: this(time.hour, time.Minute, time.Second)
{
Console.Log("and then this constructor is called after");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With