Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatic property with default value [duplicate]

Tags:

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

like image 265
Dercsár Avatar asked Jan 14 '11 14:01

Dercsár


People also ask

Can we set Default value in property c#?

You can assign the default value using the DefaultValueAttribute attribute, as shown below.

What is an automatic property and how is it useful 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. We can use attributes in many cases but often we need properties because features in different .

When can we use automatic properties?

11 Answers. Show activity on this post. Automatic Properties are used when no additional logic is required in the property accessors.


2 Answers

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).

like image 127
Jon Skeet Avatar answered Oct 23 '22 03:10

Jon Skeet


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; } }
like image 24
BrokenGlass Avatar answered Oct 23 '22 03:10

BrokenGlass