How to convert an enum value to a string? [duplicate]

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'.

5

2 Answers

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;
2

Form.Align is not a value of TPersistent. It's a value of TAlign which is an enumeration type.

You can convert an enumeration value to a string with this piece of code:

type TEnumConverter = class
public class function EnumToInt<T>(const EnumValue: T): Integer; class function EnumToString<T>(EnumValue: T): string;
end;
class function TEnumConverter.EnumToInt<T>(const EnumValue: T): Integer;
begin Result := 0; Move(EnumValue, Result, sizeOf(EnumValue));
end;
class function TEnumConverter.EnumToString<T>(EnumValue: T): string;
begin Result := GetEnumName(TypeInfo(T), EnumToInt(EnumValue));
end;

You need to add System.TypInfo to the uses.

Do this to get Form.Align as string:

S := TEnumConverter.EnumToString(Form.Align)
7

You Might Also Like