1

I'm wondering what is the cleanest way to make a property return the value specified in its DefaultValueAttribute if not initialized.

For example, I would like the getter of this property to return 42 if not initialized:

[DefaultValue(42)]
public int MyProperty { get; set; }

Any solution / refactored code welcomed. Target is .Net 4 (if greater, please indicate a fallback)

Ultimately, the aim is to avoid "hardcoding" the default value twice in order to facilitate maintenance. Also note that in a real scenario, there would be several such properties in one class. So ideally, I would prefer to avoid a solution that manually lists and initializes each properties to its default value.

Gyum Fox
  • 3,287
  • 2
  • 41
  • 71
  • Possible solution: http://stackoverflow.com/a/6444527/1010492 – Gyum Fox Aug 07 '14 at 07:45
  • I can only see one solution there that uses the DefaultValueAttribute (uses TypeDescriptor to initialize the properties that have a default value in the constructor). Any other solution? Any way to work on the property getters instead? – Gyum Fox Aug 07 '14 at 07:54
  • Can do `System.ComponentModel.DefaultValue(42)` – Nikhil Agrawal Aug 07 '14 at 07:56

0 Answers0