I just received C# in Depth by Jon Skeet in the mail and am not following the discussion on page 7-8.
We now have a private parameterless constructor for the sake of the new property-based initialization. (p. 8)
It is not clear to me how the property-based initialization requires a parameterless constructor, if that's what "for the sake of" implies.
class Product
{
public string Name { get; private set;}
public decimal Price { get; private set;}
public Product (string name, decimal price)
{
Name = name;
Price = price;
}
Product(){}
.
.
.
}
What is the purpose of Product(){}
?
This code:
Product p = new Product { Name = "Fred", Price = 10m };
is equivalent to:
Product tmp = new Product();
tmp.Name = "Fred";
tmp.Price = 10m;
Product p = tmp;
So the parameterless constructor is still required - it's only called from within the class in the sample code, so it's okay for it to be private.
That's not to say that all object initializers require a parameterless constructor. For example, we could have:
// Only code within the class is allowed to set this
public string Name { get; private set; }
// Anyone can change the price
public decimal Price { get; set; }
public Product(string name)
{
this.Name = name;
}
And then use that like this, from anywhere:
Product p = new Product("Fred") { Price = 10m };
There's a lot more detail later on in the book, of course (chapter 8 IIRC).
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