0

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 ?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.