Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 669
M610 Avatar asked Oct 30 '15 20:10

M610


People also ask

Can enum be converted to string?

We can convert an enum to string by calling the ToString() method of an Enum.

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

How do I convert an enum to a string in C++?

The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.

How do you read the enum value of a string?

SOLUTION: int enumValue = 2; // The value for which you want to get string string enumName = Enum. GetName(typeof(EnumDisplayStatus), enumValue);


1 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;
like image 82
Jens Borrisholt Avatar answered Oct 02 '22 03:10

Jens Borrisholt