Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have enum values with spaces? [duplicate]

How can I achieve the following using enums in .NET? I would like to have descriptions for each value that include spaces.

public enum PersonGender     {         Unknown = 0,         Male = 1,         Female = 2,         Intersex = 3,         Indeterminate = 3,         Non Stated = 9,         Inadequately Described = 9     } 

I would like to be able to choose whether to use either the description or integer each time I use a value of this type.

like image 343
CJ7 Avatar asked Mar 17 '13 06:03

CJ7


People also ask

Can enum values have spaces?

Unfortunately having values with spaces is not possible in enums.

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can enum names have spaces?

Sometimes you might need to loop on the elements of a particular enum and print its element names, however as you know by the language constraints, the enum element names must follow the naming convention, you cannot include spaces or other special characters.

Can enum values have spaces Java?

You can't put a space in the middle of an identifier. Doing so ends that identifier and the parser assumes whatever comes next is a valid token in that statement's context. There are few (if any) places that would be legal.


2 Answers

No that's not possible, but you can attach attributes to enum members. The EnumMemberAttribute is designed exactly for the purpose you described.

public enum PersonGender {     Unknown = 0,     Male = 1,     Female = 2,     Intersex = 3,     Indeterminate = 3,      [EnumMember(Value = "Not Stated")]     NonStated = 9,      [EnumMember(Value = "Inadequately Described")]     InadequatelyDescribed = 9 } 

For more information on how to use the EnumMemberAttribute to convert strings to enum values, see this thread.

like image 62
p.s.w.g Avatar answered Sep 21 '22 10:09

p.s.w.g


This is easy. Create an extension method for your string that returns a formatted string based on your coding convention. You can use it in lots of places, not just here. This one works for camelCase and TitleCase.

    public static String ToLabelFormat(this String s)     {         var newStr = Regex.Replace(s, "(?<=[A-Z])(?=[A-Z][a-z])", " ");         newStr = Regex.Replace(newStr, "(?<=[^A-Z])(?=[A-Z])", " ");         newStr = Regex.Replace(newStr, "(?<=[A-Za-z])(?=[^A-Za-z])", " ");          return newStr;     } 
like image 21
theMayer Avatar answered Sep 20 '22 10:09

theMayer