Why do I get "type has no typeinfo" error with an enum type

Viewed 8591

I have declared the following enum type in which I want the first member to have the ordinal value of 1 (one) rather than the usual 0 (zero):

  type
    TMyEnum = (
               meFirstValue = 1,
               meSecondValue,
               meThirdValue
              );

If I call TypeInfo(), e.g. as part of a call to GetEnumName(), I get a compiler error:

  GetEnumName(TypeInfo(TMyEnum), Ord(aValue));

ERROR: "E2134: Type 'TMyEnum' has no typeinfo"

Why is this?

I know that classes only have typeinfo if they are compiled with the $M compiler option enabled or (derive from some class which was, such as TPersistent) but I didn't think there were any special conditions for having typeinfo for enum types.

3 Answers

When you want to convert enums into specific values (and back) I useally create an array const, with the desired values per enum value:

Const MyEnumValues: array[TMyEnum] of integer = (1,2,5);

This way when the enum gets expanded you get an compiler error stating you are missing an array value.

Please note when changing the order of the enums, you must change the values accordingly.

To get the ‘value’ for an enum values just write:

Value := MyEnumValues[myenum];

And to get the enum value based on the ‘value’ just loop though the values of MyEnumValues:

Function GetEnumByValue(value:integer): TMyEnum;
Var
  myenum: TMyEnum;
Begin
  For myenum = low(TMyEnum) to high(TMyEnum) do
    If MyEnumValues[myenum] = value then
      exit(myenum);
  Raise exception.create(‘invalid value for tmyenum’);
End;
Related