Search code examples
c#propertiesinitializationfielddefault-value

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.


Solution

  • 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; } }