Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an elegant way to set a default value for a property in c#?

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.

like image 862
Jeremy Larter Avatar asked Jun 30 '10 03:06

Jeremy Larter


People also ask

How do I set default value in property?

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.

What is the default value property?

The DefaultValue property specifies text or an expression that's automatically entered in a control or field when a new record is created.

What is an Auto Property C#?

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.


1 Answers

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; } }
like image 152
Joe Enos Avatar answered Oct 02 '22 12:10

Joe Enos