Amutha Amutha - 8 months ago 91
C# Question

Private constructor and public parameter constructor

I heard that a private constructor prevents object creation from the outside world.

When I have a code

public class Product
public string Name { get;set;}
public double Price {get;set;}

public Product(string _name,double _price)

Here I still can declare a public constructor (parameter), won't it spoil the purpose of the private constructor? When do we need both private and public constructor (parameter) in code?

I need a detailed explanation please.


The reason you would use the pattern you're describing is when you want to control how the object is instantiated.

In your example, for instance, you're saying the only way to create a Product is by specifying its name and price. This is with respect to the outside world, of course. You could also do something similar using other access modifiers, and it would have different implications, but it all boils down to controlling how you want the objects instantiated with respect to who will be doing it.

If you wanted to prevent object creation altogether you would have to make all your constructors private (or protected). That would force the object to be created from within itself (or an inherited class).

Also, as Matti pointed out in the comment below, when you define a constructor that is parameterized you don't need to specify a private default constructor. At that point it is implied.