Possible Duplicate:
How do you give a C# Auto-Property a default value?
Is there any nice way to provide a default value for an automatic property?
public int HowHigh { get; set; } // defaults to 0
If not explicitly set anywhere, I want it to be 5. Do you know a simple way for it? E.g. I could set it in constructor or something, but that's not elegant.
UPDATE: C# 6 has got it: http://geekswithblogs.net/WinAZ/archive/2015/06/30/whatrsquos-new-in-c-6.0-auto-property-initializers.aspx
No, there isn't any nice way of doing this - basically you have to set it in the constructor, which isn't pleasant.
There are various limitations to automatic properties like this - my biggest gripe is that there isn't a way to create a read-only automatic property which can be set in the constructor but nowhere else (and backed by a readonly field).
Best you can do is set it in the constructor, you cannot make changes within automatic properties, you will need a backing field and implement the setter/getter yourself otherwise.
Using a backing field you can write something like this:
private int _howHigh = 0;
public int HowHigh { get {return _howHigh; } set { _howHigh = value; } }
If the default value for the type is not sufficient, then the only way to do it is via a constructor.
In a word: No.
Automatic properties are a one trick pony, as soon as you need something extra (like a reasonable default value) you should revert to the backing field regular properties.
I'm a Resharper user, and it makes going from automatic to backed properties a breeze.
The constructor is NOT the only option you have.
I believe this is best:
private int m_HowHigh = 5;
public int HowHigh {
get { return m_HowHigh; }
set { m_HowHigh = value; }
}
I prefer this for readability purposes more than the ctor().
This is NOT what you want:
[DefaultValue(5)]
public int HowHigh { get; set; }
Reference: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx#Y2248
Because this is only a decoration and does not set the value (in C#4).
精彩评论