Reputation: 3
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 ?
Upvotes: 0
Views: 2011
Reputation: 4862
Absolutely fine.
For more flexibility (e.g. if price isnt required), you can also do this with object initialization:
class Foo
{
public Foo() {}
public int Price { get; set; }
}
var newFoo = new Foo(){ Price = someVariable };
See: https://msdn.microsoft.com/en-us/library/bb397680.aspx
Upvotes: 1
Reputation: 1500515
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.
Upvotes: 3