Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding a constructor

Tags:

c#

constructor

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.

like image 234
jason Avatar asked May 28 '26 21:05

jason


1 Answers

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");
}
like image 58
Caleb Avatar answered May 31 '26 14:05

Caleb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!