elector
elector

Reputation: 1339

A list class to store enums?

What List type I should use to store enum values? I have tried with TObjectList, I cast to TObject to Add the value, but can't cast it back to enum when reading from the list.

What list do you use to store enums?

Upvotes: 8

Views: 1744

Answers (3)

Cosmin Prund
Cosmin Prund

Reputation: 25678

Casting enums to Pointer or TObject and back works just fine. If your Delphi version supports generics use Tim's suggestion, it's better. Alternatively you can use an dynamic array (array of TTestEnum) or create a wrapper class around the dynamic array - that's how generic lists are implemented in Delphi versions capable of generics.

Here's a quick console demo, using TList, not TObjectList because TList makes fewer assumptions about the items it holds.

program Project1;

{$APPTYPE CONSOLE}

uses SysUtils, Classes;

type TTestEnum = (enum1, enum2, enum3, enum4);

var L: TList;
    i: Integer;
    E: TTestEnum;

begin
  L := TList.Create;
  try
    L.Add(Pointer(enum1));
    L.Add(Pointer(enum2));
    L.Add(Pointer(enum3));
    L.Add(Pointer(enum4));
    for i:=0 to L.Count-1 do
    begin
      E := TTestEnum(L[i]);
      case E of
        enum1: WriteLn('enum1');
        enum2: WriteLn('enum2');
        enum3: WriteLn('enum3');
        enum4: WriteLn('enum4');
      end;
    end;
  finally L.Free;
  end;
  ReadLn;
end.

Upvotes: 6

Tim Ebenezer
Tim Ebenezer

Reputation: 2724

Could you not just use Generics for this?

TList<TEnumName>;

Upvotes: 5

Ken White
Ken White

Reputation: 125757

This answer may help. It's about storing records in a TList by creating a descendant to avoid all the typecasting. Note that you won't need to worry about allocating/freeing memory for the enum values, as they're simple ordinal types that fit in the space of a pointer.

Note that you have to typecast to Pointer when Adding to the list, and may have to typecast as `YourEnum(Integer(List[Index])) when reading back. However, the code I linked to shows how to handle both in the descendant class so it's only done once each way, and that's buried in the class implementation.

Upvotes: 1

Related Questions