I know the following is not possible because it has to be an int
enum GroupTypes
{
TheGroup = "OEM",
TheOtherGroup = "CMB"
}
From my database I get a field with incomprehensive codes (the OEM and CMB's). I would want to make this field into an enum or something else understandable. Because the target is readability the solution should be terse.
What other options do I have?
Answer by Even:
Just wanted to add a way how to mimic switch with class based enums:
Have you considered a lookup table using a Dictionary?
You can then use GroupTypeLookup.TryGetValue() to look up a string when you read it.
You can use two enums. One for the database and the other for readability.
You just need to make sure they stay in sync, which seems like a small cost. You don't have to set the values, just set the positions the same, but setting the values makes it very clear the two enums are related and prevents errors from rearranging the enum members. And a comment lets the maintenance crew know these are related and must be kept in sync.
To use it you just convert to the code first:
Then if you want to make it even more convenient you can add an extension function that only works for this type of enum:
and you can then just do:
You could also use the extension model:
Your Extension Class
usage:
I even implemented a few enums as suggested by @Even (via
class X
andpublic static X
members), just to find out later that these days, starting .Net 4.5, there's the rightToString()
method.Now I'm reimplementing everything back to enums.
You can add attributes to the items in the enumeration and then use reflection to get the values from the attributes.
You would have to use the "field" specifier to apply the attributes, like so:
You would then reflect on the static fields of the type of the enum (in this case GroupTypes) and get the
DescriptionAttribute
for the value you were looking for using reflection:I opted to return the
DescriptionAttribute
itself above, in the event that you want to be able to determine whether or not the attribute is even applied.