How to convert an enum value to a string?

M610 picture M610 · Oct 30, 2015 · Viewed 20k times · Source

I know I have been able to do this before, long ago, so it must be possible.

I'd like to convert an item, such as a component's align property alNone, to a string that I can save, display, whatever. I know I can get the byte value and the come up with my own text, but I'm sure there is a more direct way.

For example I want to...

var S:string;
S:= somehow(Form.Align);
ShowMessage(S);

where "somehow" is however it is I convert the setting for the form's align property to a string such as "alNone'.

Answer

Jens Borrisholt picture Jens Borrisholt · Oct 30, 2015

You can convert between enum types and String back and forth using RTTI :

uses
  RTTI;

procedure TForm40.FormCreate(Sender: TObject);
var
  sAlign: string;
  eAlign: TAlign;
begin
  //Enum to string      
  sAlign := TRttiEnumerationType.GetName(Align);
 
  //string to enum
  eAlign := TRttiEnumerationType.GetValue<TAlign>(sAlign);
end;