Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor Initialization of Properties in C#

Tags:

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; } }
 }
like image 456
Konrad Reiche Avatar asked Dec 17 '25 16:12

Konrad Reiche


1 Answers

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.

like image 188
BenCr Avatar answered Dec 20 '25 06:12

BenCr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!