3
votes

Is it possible to have a stringlist in a record? EG

TImportStats = record
  ATotal:Integer;
  BTotal:String;
  AList:TStringist;
end;

and if I presume I would need to create it before using the record?

4

4 Answers

7
votes

Whilst this is perfectly legal, it may be prudent to find another way. You pinpoint the issue when you said:

I presume I would need to create it before using the record

Not only that, but you need to find a good time to destroy it too. If you forget to do so there will be no errors but your program will leak memory.

If the record is the owner of the string list then you may be better off containing it inside a class. That way the construction and destruction of the string list will follow the constructor/destructor pattern that all Delphi developers are familiar with.

If the record does not own the string list, but just takes a reference to it during the lifetime of the string list, then a record is fine. But if you do it this way make sure that the record's lifetime is contained within the string list's lifetime so that you don't carry around a stale reference.

3
votes

Yes, this should work. AList will (not be useable) until you create the stringlist. So you can use other elements of the record without creating the stringlist, but you must create the stringlist element prior to using it. Also, you are responsible for freeing each stringlist when you're done.

0
votes

If the stringlist is only going to be used in the local scope of the TImportStats record, you might want to look at a StringList value implementation in Code Central.

This avoids the try, create, finally, destroy overhead.

0
votes

I know it's probably late, but the most elegant way to solve your problem, would be to create a subclass of TStringList with ATotal and BTotal as the two new elements in it. Then you can simply create and destroy it as you see fit. This solution is clean and simple.