Delphi Programming

and software in general.

Friday, April 8, 2011

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<TEnumType> = class
    class function Name(const Enum:TEnumType):String;
    class function Value(const Ordinal:Integer):TEnumType;
  end;

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

class function TEnumGen<TEnumType>.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.