How to have enum values with spaces?
Solution 1
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.
Solution 2
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;
}
Solution 3
var assembly = Assembly.LoadFrom("ResourcesLib.DLL");
var resourceManager =
new ResourceManager("ResourcesLib.EnumDescriptions", assembly);
var lst = Enum.GetValues(typeof(PersonGender)).Cast<PersonGender>().ToList();
foreach (var gender in lst)
{
Console.WriteLine(gender); // Name
Console.WriteLine((int)gender); //Int Value
Console.WriteLine(resourceManager.GetString(gender.ToString()));//localized Resorce
}
So spaces may reside in localized resource ...
CJ7
Updated on March 17, 2020Comments
-
CJ7 about 4 years
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.