Konrad Reiche
Konrad Reiche

Reputation: 29493

Constructor Initialization of Properties in C#

When initializing members in a C# class which also have Properties with full access (get, set), is it convention to initialize them inside the constructor via their Property method or directly by their member variable?

public class Car
{
    private string _brand;

    public Car(string brand)
    {
        // this
        _brand = brand;
        // or that
        Brand = brand;  
    }

    public Brand { get { return _brand; } set { _brand = value; } }
 }

Upvotes: 3

Views: 5940

Answers (7)

BenCr
BenCr

Reputation: 6052

You should set the value using the Property and not the member variable. This way you can change the implementation of your "setter" and only have to modify the your code in one place.

For example, if you discover a requirement that on setting the brand you have to also update some other property, the brand has a default colour for example, you can do this all in your set{...} block of the Brand property. If you set the value of _brand in your contructor, you'll now have to either manually update the Colour property in the constructor as well, or update your constructor to now initialise the Brand property instead of the field.

Also, where your property is that simple it's more conventional to use an "auto property"

public Brand { get; set; }

I'd only use a backing field if you need to perform more logic than a simple property set and get.

Upvotes: 4

rusty
rusty

Reputation: 2789

I always use the property accessors, because then your code is more prepared for changes down the road. For instance, as others have pointed out, the code you provided here can be rewritten using auto-properties. Additionally, if you use the property accessors throughout the class, you can then change the implementation of the property down the road and you'll only have to change code in one place.

Upvotes: 2

Mutation Person
Mutation Person

Reputation: 30498

When you construct a class it should be ready for use and requiring no further initialisation actions.

If your properties must be initialised in some way then this should be done via the constructor.

Upvotes: 1

Michael Minton
Michael Minton

Reputation: 4495

Use the internal variable unless you have specific code in the Set method for the property that needs to fire.

Upvotes: 2

keyboardP
keyboardP

Reputation: 69372

In the constructor, I prefer _brand = brand. I see getters and setters as methods to be called by external classes. There's also slightly less overhead as you're avoiding an extra method call.

Upvotes: 0

Martin
Martin

Reputation: 150

I suggest their member variable, it's one less call on the stack.

Upvotes: 0

Ryan Bennett
Ryan Bennett

Reputation: 3432

I've always done/seen the _brand = brand way. It makes sense, you are setting the internal state of the class. The properties are for external access.

Upvotes: 0

Related Questions