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?
My first question - Do you have access to the Database itself? This should be normalized in the database, ideally, otherwise, any solution is going to be prone to error. In my experience, data fields full of "OEM" and "CMB" tend to wind up having things like "oem " and other 'crap data' mixed in over time.... If you can normalize it, you could use the key in the table containing the elements as your Enum, and you're done, with a much cleaner structure.
If that's not available, I'd make your Enum, and make a class to parse your string into the Enum for you. This would at least give you some flexibility in handling non-standard entries and much more flexibility for trapping or handling errors than doing any of the workarounds using Enum.Parse/Reflection/etc. A dictionary would work, but could break down if you ever have case issues, etc.
I'd recommend writing a class so you can do:
This preserves most of your readability without having to change the DB.
Why not just use ToString() on the Enum types?
I was basically looking for the Reflection answer by @ArthurC
Just to extend his answer a little bit, you can make it even better by having a generic function:
Then you can just wrap whatever you have
or
I would make it into a class an avoid an enum altogether. And then with the usage of a typehandler you could create the object when you grab it from the db.
IE:
I didn't need anything robust like storing the string in attributes. I just needed to turn something like
MyEnum.BillEveryWeek
into "bill every week" orMyEnum.UseLegacySystem
into "use legacy system"--basically split the enum by its camel-casing into individiual lower-case words.MyEnum.UseLegacySystem.UnCamelCase()
outputs "use legacy system"If you have multiple flags set, it will turn that into plain english (comma-delimited except an "and" in place of the last comma).