Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of private parameterless constructor in C#

Tags:

c#-3.0

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(){} ?

like image 234
Tim Avatar asked Jan 14 '23 14:01

Tim


1 Answers

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).

like image 91
Jon Skeet Avatar answered Apr 30 '23 12:04

Jon Skeet