Return all enum items as a TStringList

176 views Asked by At

My function EnumToStringList() on its own can be compiled, but I can't call it with any enum type in my app:

[dcc64 Error] Unit_test.pas(119): E2029 '(' expected but ')' found

What is wrong with my approach?

function EnumToStringList(const TypeInfo: pTypeInfo): TStringlist;
var  i : Integer;
begin
  Result := TStringList.Create;
  for i := GetTypeData(TypeInfo)^.MinValue to GetTypeData(TypeInfo)^.MaxValue do
    begin
      result.add (GetEnumName(TypeInfo, i));
    end;
end;
        
function EnumToString(const TypeInfo: pTypeInfo; Ix: Integer): string;
begin
  result := GetEnumName(TypeInfo, Ix);
end;
    
type
  TProjectTypes = (low,hot,skip,pause,others);

// test code:
MyProjectStrings := EnumToStringList (TProjectTypes);
2

There are 2 answers

1
Dalija Prasnikar On BEST ANSWER

You cannot directly pass enumeration type to your function. You need to get its type info first by calling TypeInfo on it.

  var
    MyProjectStrings := EnumToStringList(TypeInfo(TProjectTypes));
0
complete_stranger On

This should work:

implementation

uses
  System.TypInfo;

procedure EnumToStringList (Sender: TObject);

type
  TProjectTypes = (low, hot, skip, pause, others);

var
  pt: TProjectTypes;
  sl: TStringList;
begin
  sl := TStringList.Create;
  try
    for pt := System.Low(TProjectTypes) to System.High(TProjectTypes) do
      sl.Add(GetEnumName(TypeInfo(TProjectTypes), ord(pt)));

    ShowMessage(sl.Text);
  finally
    sl.Free;
  end;
end;

One guess: You work with System.Low at some point but you redefine low with your TProjectTypes. Just put a System. infront of your Low.