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?
Using an ArrayList of Enum Values. We can also create an ArrayList by using Arrays. asList().
Yes. If you do not care about the order, use EnumSet , an implementation of Set . enum Animal{ DOG , CAT , BIRD , BAT ; } Set<Animal> flyingAnimals = EnumSet.
As enum types are handled as integral types, they are stored in the stack and registers as their respective data types: a standard enum is usually implemented as an int32; this means that the compiler will handle your enum as a synonym of int32 (for the sake of simplicity, I left out several details).
Put the enums in the namespace where they most logically belong. (And if it's appropriate, yes, nest them in a class.)
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.
Could you not just use Generics for this?
TList<TEnumName>;
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 Add
ing 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With