What's the easiest (ie., least coding) way to map an enum to a const string and vice versa? (Can attributes be used on enum values yet?)

What's the easiest (ie., least coding) way to map an enum to a const string and vice versa? (Can attributes be used on enum values yet?)

eg., type TMyColors = (mcRed, mcGreen, mcBlue);

How to do:

TMyColors[mcRed].AsString --> 'Red'

and

TMyColors['Red'] --> mcRed

I know these are not syntactically correct, but you get the idea.

(I realize it's easy to use a Case stmt on a TMyColors value to get a string, but the opposite is not possible since we can't use strings as Case discriminants, which requires a lengthy if...then...else if ... mess, or an array.)

Comments

  1. Agustin Ortu That attributes example is a terrible mess, IMO. String literals that compiles fine, but that have a high risk for run time errors.

    ReplyDelete
  2. It's super easy to test. A little unit test will throw such runtime error in a glimpse.

    On the other hand, a case statement has the very same problem. The most compile safe check is Stefan's approach, but you will need specific routines to handle conversion, plus you loose object oriented syntax.

    Btw I'm not claiming my approach is the best; we all agree that the language should provide a better built in mechanism as Stefan said. But different needs may use different approaches. For complex things I'll go with what Jeroen said and write specific classes. I might even go further and drop the enums at all and use objects

    For me, it's just a matter of a stupid UI <--> value matching and this worked just fine for me. I sense that the OP need is the same and hence shared it.

    ReplyDelete
  3. It's great to see all of these different variations, and I know there are more -- these are just the less obvious ones.

    Which only just proves my point that there's a lot of programmer time wasted in crafting solutions around simple things like that should be supported by the compiler, but aren't.

    ReplyDelete

Post a Comment