3

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.

Sam
  • 7,252
  • 16
  • 46
  • 65
jason
  • 6,962
  • 36
  • 117
  • 198
  • possible duplicate of [this statement after contructor's arguments](http://stackoverflow.com/questions/16861231/this-statement-after-contructors-arguments) – GSerg Jun 14 '14 at 08:22
  • 1
    When a class declares more than one (non-static) constructor, we have an example of _overloading_. In that case one of the constructor overloads can _chain_ another one with the syntax you mention. The body of the constructor that is chained (in your example `Time2(int, int, int)`) runs first, after that the body of the chaining constructor (here `Time2(Time2)`) runs (that body was empty `{ }` in your example). – Jeppe Stig Nielsen Jun 14 '14 at 08:39

3 Answers3

5

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");
}
Caleb
  • 1,088
  • 7
  • 7
  • 1
    This syntax is also used to call constructors in a base class when using inheritance. Instead of `this`, the keyword `base` is used. (and the corresponding constructor in the base call will be called before executing the code in the constructor on the inherited class. – Caleb Jun 14 '14 at 08:24
4

That is called constructor chaining and calls the that specific constructor before executing the code in that constructor.

You can also use :base and this calls the relevant constructor in the base class (if your class extends anything of course)

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
1

This constructor will call the first constructor using the data from the given Time2 instance.

Code:

Time2 TwoHours = new Time2(2, 0, 0);
TwoHours.SetTime(0, 120, 0);
Time2 2Hours = new Time2(TwoHours);

// 2Hours will have 0 Hours, 120 Min and 0 Seconds
Community
  • 1
  • 1
Monacraft
  • 6,510
  • 2
  • 17
  • 29