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.
Unfortunately having values with spaces is not possible in enums.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
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.
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.
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.
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; }
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