Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does memo.Lines use TStrings instead of TStringList?

Tags:

Why does Memo.Lines use the abstract class TStrings? Why doesn't it use TStringList instead?

And should I convert it to TStringList before working with it?

like image 434
Illiou Avatar asked Jun 20 '12 14:06

Illiou


1 Answers

TMemo.Lines, TListBox.Items, TComboBox.Items, etc. ; all are declared as TStrings. Beware, talking about the property that is! The internal created types are TMemoStrings, TListBoxStrings and TComboBoxStrings respectively, which are all descendants of TStrings and differ all in way of storage.

And why? For interchangeability and interoperability. So every TStrings-descendant has the same properties, and so you can do:

Memo1.Lines := ListBox1.Items;

How to use? Well, a TStrings property like TMemo.Lines works just fine. You can add, delete, change, renew and clear the strings (and objects) on the property, because internally it is a TMemoStrings which implements all this interaction. Declaration <> implementation.

But when you want any special handling, e.g. like sorting which TStringList provides, then you need help. You cannot typecast nor convert a TMemo.Lines to a TStringList, because it isn't one, but instead you need to create an intermediate object for this special processing:

var
  Temp: TStringList;
begin
  Temp := TStringList.Create;
  try
    Temp.Assign(Memo1.Lines);
    Temp.Sort;
    Memo1.Lines.Assign(Temp);
  finally
    Temp.Free;
  end;
end;
like image 182
NGLN Avatar answered Sep 18 '22 05:09

NGLN