Search code examples
delphidelphi-xe8

Enumerations (with custom values) to String / Text


One can use something like this to convert an enum to string:

uses
TypInfo;

type
  Language = (Delphi,Delphi_Prism,CBuilder);

var
  StrLanguage : String;
begin
  StrLanguage  := GetEnumName(TypeInfo(Language),integer(Delphi)) ; 
end;

(taken from theroadtodelphi)

Is it possible to do the same for an enum that has custom values?

Something like this:

type
  THotkey = (hkShift= 1, hkSpace= 3, hkEnter= 6);

As a workaround i am using placeholders to skip not used enums.

However that's not nice and is problematic if i have to skip huge gaps.

type
  THotkeys = (hkShift, hkUnused1, hkSpace, hkUnused2, hkUnused3, hkEnter);

Solution

  • In your specific use case, you could use an array that relates to the enum, because enumerated constants with a specific value do not have RTTI as stated in the documentation:

    Enumerated constants without a specific value have RTTI:

    type SomeEnum = (e1, e2, e3);
    

    whereas enumerated constants with a specific value, such as the following, do not have RTTI:

    type SomeEnum = (e1 = 1, e2 = 2, e3 = 3);
    

    You can work around this like so:

    type
      THotkey = (hkShift, hkSpace, hkEnter);
      THotkeyValues: array[Thotkey] of Integer = (1,3,6);
    

    usage:

    ShiftKeyValue := THotkeyValues[hkShift];