Skip to content

Converting Delphi enumerated values to strings

It’s pretty easy to converted Delphi enumerated types to string and vice versa, but I can never remember the syntax.  The good thing about having your own blog is being able use it as an off-line cranial storage device.  I did the same thing a while back to do the same thing in .NET code.

To convert an enumerated type to a string:

uses typinfo;
function MyTypeToString( value: TMyType ): string;
begin
    result := GetEnumName(typeInfo(TMyType ), Ord(value));
end;

 

To convert a string back to an enumerated type, the following syntax can be used

uses typinfo;
function StringToMyType(const value: string): TMyType
begin
  result := TMyStyle(GetEnumValue(Typeinfo(TMyStyle), value);
end;

 

GetEnumName and GetEnumValue are defined in typinfo, you’ll need to add that unit to the uses clause of your code.  This functionality is very useful if you ever need to implement your own object serialization routines in Delphi.