Jeremy Larter
Jeremy Larter

Reputation: 558

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.

Upvotes: 5

Views: 2984

Answers (6)

SUNIL DHAPPADHULE
SUNIL DHAPPADHULE

Reputation: 2863

I think easiest way to set default value:

public sealed class Employee
{
    public int Id { get; set; } = 10;
}

Upvotes: 7

AMissico
AMissico

Reputation: 21684

The design-pattern I use, which is used throughout Microsoft's Windows.Forms controls and other .NET Classes. Moreover, from my understanding, the initialization outside of the contructor allows just-in-time compiler to optimze the class code.

public class Foo {
    public static const int DefaultSpeed = 100;
    private int _speed = DefaultSpeed;
    [DefaultValue(DefaultSpeed)]
    public int Speed { get { return _speed; } set { _speed = value; } }
}

    public class Foo {
        public static Color DefaultForecolor { get {return SystemColors.WindowText; }}
        private Color _forecolor = DefaultForecolor;
        [DefaultValue(DefaultForeColor)]
        public Color Forecolor { get { return _forecolor; } set { _forecolor = value; } }
    }

Upvotes: 2

Stephen Cleary
Stephen Cleary

Reputation: 456507

CciSharp supports the DefaultValue attribute, which allows placing default values on auto properties. Whether CciSharp qualifies as an "elegant" solution, however, is a matter of opinion (it acts as a post-compiler that edits the IL in the binary).

Upvotes: 1

Adam Robinson
Adam Robinson

Reputation: 185643

The constructor is the only way to set the initial value of an auto property.

Upvotes: 1

Joe Enos
Joe Enos

Reputation: 40393

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

Upvotes: 7

this. __curious_geek
this. __curious_geek

Reputation: 43207

you must set the default value for the property in the constructor. There's no other way to do it besides this for automatic properties since the fields for the automatic props are declared at compile time and replaced within getter/setter. However in explicit properties, you can initialize the field the property uses to read or write as Joe mentioned in his answer.

Upvotes: 1

Related Questions