I have read that there are good reasons to use properties instead of fields in c# on SO. So now I want to convert my code from using fields to using properties.
For an instance field of a class, I can set a default value. For example:
int speed = 100;
For the equivalent property, which I think is:
int Speed { get; set; }
My understanding is that the Speed property will be initialised to zero when the class is instantiated. I have been unable to find out how to set a default value to easily update my code. Is there an elegant way to provide a default value for a property?
It seems like there should be an elegant way to do this, without using a constructor, but I just can't find out how.
Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.
The DefaultValue property specifies text or an expression that's automatically entered in a control or field when a new record is created.
Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it.
Best bet is to do a normal old-fashioned field-backed property, like:
private int _speed = 100;
public int Speed { get { return _speed; } set { _speed = value; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With