GNOME Bugzilla – Bug 595458
Enhance enum to increase its usefulness
Last modified: 2010-01-09 11:15:12 UTC
It is often nice to be able to take a value from an enumeration and output it in a program to the display (in a log file, or whatever). So, say you have: public enum AddressType { IPv4, IPv6 } And you have this somewhere: AddressType at = AddressType.IPv4; stderr.printf("Using address type %d.\n", at); This would display "Using address type 0." on stderr. However, it would be nice and more useful to do replace the above printf with this: stderr.printf("Using address type %s.\n", at); Or, if the implicit conversion is undesired: stderr.printf("Using address type %s.\n", at.to_string()); That would then show "Using address type IPv4." or something similar and just as meaningful, even if the case is altered due to the transformation into C code and C coding conventions. It seems that this *should* be possible, given that GEnum is used, and a GEnumValue (when the enum type is known) should easily resolve to a type. It would also make it possible to print "flags" type enumerations in a meaningful way, though that would be more difficult, I expect.
Try that: public string enumToString( Type enum_type, int value ) { EnumClass ec = (EnumClass) enum_type.class_ref(); unowned EnumValue ev = ec.get_value( value ); return ev == null ? "Unknown Enum value for %s: %i".printf( enum_type.name(), value ) : ev.value_name; } I'd love to see it Vala integrated, but Jürg seems to have reservations.
(as to_string() for an enum, of course, not as a seperate top-level-function)
For whatever it is worth: I completely agree with Mickey above: It would be great to be able to write enum X { ... }; X x = ...; log(..., @"... $x ..."); which would be possible if an enum would have an implicit to_string "method".
commit 1fbdecd6d5bc61c6347fc1718368a0fbbafec0c9 Author: Jürg Billeter <j@bitron.ch> Date: Sat Jan 9 12:12:22 2010 +0100 Support to_string for enums