Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare the default value of an enumerated property?

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.

like image 403
Ian Boyd Avatar asked Dec 02 '11 21:12

Ian Boyd


1 Answers

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)

like image 112
Marc Gravell Avatar answered Nov 06 '22 15:11

Marc Gravell