Requirement
I want to select values from an enum
in C# using a ComboBox
or select bitmasks (for enum
s with the Flags
attribute) with a CheckedListBox
. I want a way to add the values to the controls as selectable items, and cleanly tell which the user has selected.
Objective 1: User-friendly
I also want the selection to be clear and pretty to the user. Currently I can already add Enum
values to a ComboBox
or a CheckedListBox
, but Enum.ToString()
will return the identifier name. Pascal Case is good enough for me, but not for my users.
Objective 2: Easy to code
I want this to be easy to code. I mean easy. I want this to be a mere afterthought to defining and/or using any enum
value.
My Solution
Now I looked around and saw several nice solutions. Some of them are better in their own ways, like if you really need to put in your own custom descriptions, or to take it one step further, support multiple languages. You can do fake enums too. But I kept looking, and none of them had quite the combination of elegance and simplicity--for my purposes--as what I wrote. See below.
The basis of my solution is a
struct
that can wrapEnum
values and overrideToString()
.Enter the
EnumWrapper
:The method
ToStringFriendly()
is defined as an extension method onEnum
:Now, to add any
Enum
value to a ComboBox, for example,And to get it back out (after null-testing, of course):
And that's it. Now what are the pros and cons of this approach?
The Pros:
EnumWrapper
.Enum
values with a few special cases. One example might be a value calledMyValue__DescriptionOf123_ENUMValue
which would come out ofToStringFriendly()
as "My Value: Description of 123-ENUM Value".struct
and an extension method) can be written once and tucked out of the way. There is no additional coding in eachEnum
. This means it works nicely as above for enums you didn't write, assuming Pascal case, which in .NET is a good assumption. Note: This is why I'd say this answer, however elegant, is not a better solution than mine, as it requires that you can add aTypeConverter
attribute to eachEnum
.The Cons:
Encoding.EBCDIC
will always come through as "EBCDIC" and does not allow you to manually type "Extended Binary Coded Decimal Interchange Code", much less other languages.Future Work
One could add custom descriptions and multi-language support by changing
ToStringFriendly()
to do a language-lookup for that value before de-Pascal-casing.For more Regex fun, see this thread.