Let's say that you have to use an constructor to initialize some fields...
class Foo
{
private int price;
public Foo(int price)
{
this.price = price;
}
}
I know that usually the constructor initializes some fields but what's the difference if I initialize properties with it. For example
class Foo
{
private int price { get; set; }
public Foo(int price)
{
this.price = price;
}
}
The code seems to work the same but my question is if this is good practice and should I do it ?
It's fine for a constructor to initialize properties, but it's rarely useful to have private automatically-implemented properties. I'd always use properties rather than fields for non-private state (whether those properties are automatically implemented or not) and private properties make sense when they're non-trivial, e.g. performing validation or some other computation. But I'd only turn a private field into a private automatically-implemented property if I wanted it for something like a reflection-based library that only understood properties.
See more on this question at Stackoverflow