Delphi coding hints and tips.

Enumerated types to strings using RTTI

Using the RTTI (Run-time Type Information) that the Delphi compiler generates it is possible to convert any enumerated type value to a string and vice verse. The TypInfo.pas unit within the VCL give us an interface into the RTTI generated by the compiler.

Below is a simple enumerated type for months for the year.

type
  TMonth=(Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec);

To get a value as a string of a month we use the TypInfo.pas function GetEnumName. Below is an example of code do do this.

{Add TypInfo unit to uses statement}
uses
  TypInfo;

{Set TLabel caption to string value of TMonths value May} 
Label1.Caption:=GetEnumName(TypeInfo(TMonth),Ord(May));

Note the call to TypeInfo which returns a pointer to compiler generated run-time type information for a type given, in this case TMonth. This pointer will point to TTypeInfo structure held in memory, see TypInfo.pas. The declaration of TTypeInfo in TypInfo.pas has {TypeData: TTypeData} as a comment. This is because TTypeInfo.Name is a old-style Pascal short string. Thus the position of TypeData will be variable.

To get the value given a string we use GetEnumValue as below:

var
  M:TMonth; {Get value from string}

M:=TMonth(GetEnumValue(TypeInfo(TMonth),'May'));
{Set labels caption to ordinal value of month}
Label2.Caption:=IntToStr(Integer(M));

Again a call to TypeInfo is used to get a pointer to compiled type information for TMonth. The GetEnumValue function returns an Integer so have to cast back into a TMonth.