Delphi pitfalls: Enumerated types and for loops

Not all for loops are created equal.

Consider
for x in [value1, value2, value3]

You would expect to see x vary in the order of the values in the list.

However – if x and the values are of an enumerated type, looping the “list”
does NOT loop in the apparent order of the constant, but in the order of the enumerated type declaration, such as it would for any set.

Continue reading “Delphi pitfalls: Enumerated types and for loops”

Generics, Enumerated types and ordinal values

I wish this was a solution post, but it is a frustration post. I trying to figure out how I can use Ord() to convert an enumerated type to integer or cast an integer to an enumerated type using generics type arguments?

uses
SysUtils,
TypInfo;

type
TSomeEnumType = (TheFirst, TheSecond, TheThird, TheFourth);

type
TEnumGen = class
class function Name(const Enum:TEnumType):String;
class function Value(const Ordinal:Integer):TEnumType;
end;

class function TEnumGen.Name(const Enum: TEnumType): String;
begin
Result := Format('%s.%s',
[GetTypeName(TypeInfo(TEnumType)),
GetEnumName(TypeInfo(TEnumType), Ord(Enum)) // <-- Bombs
]);
end;

class function TEnumGen.Value(const Ordinal:Integer):TEnumType;
begin
Result := TEnumType(Ordinal); // <- Bombs
end;

Unfortunately there is no “enum” delimiter that can be used to tell the compiler that Ord() and casting of integers should be allowed for generic enumerated type arguments.