Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a set in a TStringList Object?

Tags:

delphi

I'm trying to store a set inside the object property (and read it) of a TStringList (I will also use it to store text associated to the set) but I get a invalid typecast for the set.

What's the best way to store a set inside a StringList object? Also, will this object need to be freed when destroying the StringList?

Here's some example code:

type
 TDummy = (dOne, dTwo, dThree);
 TDummySet = set of TDummy;


var
  DummySet: TDummySet;
  SL: TStringList;
begin
  SL := TStringList.Create;
  Try
    DummySet := [dOne, dThree];
    SL.AddObject('some string', TObject(DummySet)); // Doesn't work. Invalid typecast
  Finally
    SL.Free;
  End;
end;
like image 980
smartins Avatar asked Dec 22 '22 05:12

smartins


1 Answers

First read the other answers - probably you'll find a less hacky solution.

But FTR: You can write

SL.AddObject('some string', TObject(Byte(DummySet)));

and

DummySet := TDummySet(Byte(SL.Objects[0]));

if you really want.

Note: You'll have to change the keyword Byte if you add enough elements to the TDummySet type. For example, if you add six more elements (so that there is a total of nine) you need to cast to Word.

like image 132
Uli Gerhardt Avatar answered Dec 29 '22 00:12

Uli Gerhardt