How do i set the default value of an enumerated property?
e.g.:
public enum SearchBoxMode { Instant, Regular };
[DefaultValue(SearchBoxMode.Instant)]
public SearchBoxMode Mode { get { return mode; } set { mode = value; } }
[DefaultValue((int)SearchBoxMode.Instant)]
public SearchBoxMode Mode { get { return mode; } set { mode = value; } }
[DefaultValue(SearchBoxMode.GetType(), "Instant")]
public SearchBoxMode Mode { get { return mode; } set { mode = value; } }
[DefaultValue(SearchBoxMode.GetType(), "SearchBoxMode.Instant")]
public SearchBoxMode Mode { get { return mode; } set { mode = value; } }
Unrelated question: How do i get the Type
of an enumeration? e.g.
Type type = DialogResult.GetType();
does not work.
The default value of an enum is 0 of the underyling type, even if 0 isn't defined for that enum. Anything else must be done manually, for example:
SearchBoxMode mode = SearchBoxMode.Instant; // field initializer
Using [DefaultValue(...)]
only impacts things like serialization and PropertyGrid
- it doesn't actually make the property default to that value. The correct syntax is as per your first example:
SearchBoxMode mode = SearchBoxMode.Instant;
[DefaultValue(SearchBoxMode.Instant)]
public SearchBoxMode Mode { get { return mode; } set { mode = value; } }
Another approach is a constructor:
[DefaultValue(SearchBoxMode.Instant)]
public SearchBoxMode Mode { get; set; }
public YourType() {
Mode = SearchBoxMode.Instant;
}
re the second question; typeof(DialogResult)
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