0

i can not read this line of code

public Wine (decimal price, int year) : this (price) { Year = year; }

what :this keyword do in a constructor

public class Wine
{
    public decimal Price;
    public int Year;

    public Wine (decimal price) 
    { 
        Price = price; 
    }

    public Wine (decimal price, int year) : this (price) 
    { 
        Year = year; 
    }
}
ulrichb
  • 19,610
  • 8
  • 73
  • 87
Tarek Saied
  • 6,482
  • 20
  • 67
  • 111
  • possible duplicate of [What does this colon (:) mean?](http://stackoverflow.com/questions/1071148/what-does-this-colon-mean) – cHao Sep 22 '11 at 23:03

4 Answers4

5

This is called constructor chaining. Instead of rewriting the code of the one-argument constructor, you simply call it. C# makes this simple by using this short notation with the colon.

klaustopher
  • 6,702
  • 1
  • 22
  • 25
3

this(price) calls another constructor that in this case only takes one parameter of type decimal. As a reference read "Using Constructors".

I'm not a big fan of this particular example since both constructors do initialization work.

In my opinion it is better to pass default values to one constructor that then does all the work - this way initialization is not spread between different constructors and you have a single spot where everything is initialized - a better way would be:

public class Wine
{
   public decimal Price;
   public int Year;
   public Wine (decimal price): this(price, 0)
   public Wine (decimal price, int year) 
   { 
      Price = price;
      Year = year; 
   }
}
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
0

It calls the constructor with the single decimal parameter price first.

Andreas
  • 6,447
  • 2
  • 34
  • 46
0

It calls another constructor in the same class that has that signature passing the values into it that were supplied to the initial constructor call. In you example, the Wine class has (at least) two constructors, one that takes a decimal (price) and a int (year), as well as a second one that only takes a decimal (price).

When you call the one that takes the two parameters, it calls the one that takes only one parameter passing the value of price into the second one. It then executes the constructor body (setting Year to year).

This allows you to reuse common logic that should happen no matter which constructor call was made (in this instance setting the price should always happen, but the more specific constructor also sets the Year).

Michael Shimmins
  • 19,961
  • 7
  • 57
  • 90