简体   繁体   中英

C# constructor initializing properties instead of fields?

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, eg 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.

Absolutely fine.

For more flexibility (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM