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
You can assign the default value using the DefaultValueAttribute attribute, as shown below.
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. We can use attributes in many cases but often we need properties because features in different .
11 Answers. Show activity on this post. Automatic Properties are used when no additional logic is required in the property accessors.
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 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