Enum.toString

The inverse of fromString, this function takes an enum member value and returns its string identifier.

It lowers to a big switch of the enum members. It is faster than std.conv.to and generates less template bloat.

Taken from: https://forum.dlang.org/post/bfnwstkafhfgihavtzsz@forum.dlang.org written by Stephan Koch (https://github.com/UplinkCoder). Used with permission.

Limitations: Does not work with enums whose members' values cannot be used in a switch statement. This includes enums with members that share values with other members, as well as enums of values that are non-string arrays or other complex types.

template Enum(E)
@safe pure
string
toString
()
if (
is(E == enum)
)

Parameters

value E

Enum member whose string name we want.

Return Value

Type: string

The string name of the passed enum member, or (for instance) cast(E)1234 if an invalid value of 1234 was passed, cast to type E.

Examples

enum E { a, b, c }

string a = Enum!E.toString(E.a);
string c = Enum!E.toString(E.c);

assert(a == "a");
assert(c == "c");

// Enum members must not share values
enum F { d = 1, duplicate = 1 }
//string d = Enum!F.toString(F.d);  // compile-time error

See Also