So currently have an enumeration used on the status of an application. However, something feels off when using it against the ui. To many conversions between integer and string when populating drop downs. I could use an extension method or the type converter and continue to use the enum which will be helpful if an enum has multiple words in it.
Thought I'd ask to see about filling in a possible hole before I dig it to deep.
Thanks.
My team had this issue in our recent project. We kept the enums, because they are the thing to use for a finite list of known constant values, but we did a few things to make them more developer-friendly:
So, given the following:
public enum MyItems
{
[Description("Item One")]
ItemOne,
[Description("Item Two")]
ItemTwo,
[Description("Item Three")]
ItemThree
}
we could populate a DropDownList with user-friendly choices in two lines:
foreach(MyValues value in Enum.GetValues<MyValues>())
myDDL.Items.Add(New ListItem(value.GetDescription(), value.ToString())
... and then we could parse the selection back out with very readable code:
var theValue = myDDL.SelectedItem.Value.ParseEnum<MyValues>()
EDIT: I have been asked for the GetDescription() method. I'm a little iffy about sharing the whole thing, but here's the basic algorithm for getting a Description attribute that decorates an enum constant. Parsing a CamelCased name is pretty straightforward RegEx splits on capital letters, and our implementation's a little naive anyway. This snippet requires System.ComponentModel.DescriptionAttribute (which is also the decorator for the enum constants), and enumType is the "this" parameter of the extension method, of type Enum:
var attr = enumType.GetType().GetField(enumType.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attr.Length > 0)
return ((DescriptionAttribute)attr[0]).Description;
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