Search code examples
enumsd

Get Enum Name from Value?


I just stumbled on this topic while looking for an answer to this question.

Essentially, what I'm asking is the opposite of what's done in that thread. Instead of getting an enum's value by it's name, I'd like to get it's name by it's value. How is this done?


Solution

  • You do it the exact same why, but as Eric points out, it isn't perfect:

    import std.conv;
    import std.stdio;
    
    enum LogLevel { ALL, INFO, WARNING }
    enum Color {white, gray = 1, grey =1, black}
    
    void main()
    {
         enum l = to!LogLevel(1);
         assert(l == LogLevel.INFO);
         writeln(to!string(l));
    
         enum c = to!Color(1);
         writeln(to!string(c));
    }
    

    INFO
    gray