Christian
Christian

Reputation: 723

How to use generic TList List property

DelphiXE7 Update1

While trying to work with the TList.List property I noticed an odd behavior. If you look at the following code it seems that the array size returned by MyList1.List is not correct... So, where the bug? Is it in my code/head or within the RTL ;-)

var
  MyList1, MyList2: TList<String>;
begin
  MyList1 := TList<String>.Create;
  MyList2 := TList<String>.Create;

  MyList1.Add('A');
  MyList1.Add('B');
  MyList1.Add('C');

  MyList2.AddRange(MyList1.List);   // MyList1.Count = 4 !!!!

  ShowMessage(Format('%d, %d', [MyList1.Count, MyList2.Count]));
end;

enter image description here

Upvotes: 2

Views: 926

Answers (1)

David Heffernan
David Heffernan

Reputation: 613572

The List property is the raw underlying storage. The class, as an optimisation to reduce the number of re-allocations, over allocates this storage. This has the effect that the array return by List may have more elements than the list itself. You can then add more items without forcing re-allocation until the capacity is reached.

The behaviour is thus to be expected. Use Count to find out how many items in the list are defined.

Upvotes: 3

Related Questions