bug in TEnumerableBase<T>.ToArray

Issue #234 resolved
Merijn Bosma created an issue

ToArray in TEnumerableBase<T> doesn't explicitly set the length of result to 0 in case the it's empty. Please see this snippet to reproduce:

var list1: ISet<string>;
    list2: ISet<string>;
    a: TArray<string>;
begin
 list1 := TCollections.CreateSet<string>;
 list2 := TCollections.CreateSet<string>;

 list1.Add('A');
 list1.Add('B');

 a := list1.ToArray(); //  <-- a is now ['A', 'B']
 a := list2.ToArray(); //  <-- a is now still ['A', 'B'], while it should be empty
end;

I'm not sure whether this should be considered a bug in Spring or in Delphi, but it's solved by changing TEnumerableBase<T>.ToArray:

    count := collection.Count;
    if count > 0 then
    begin
      SetLength(Result, count);
      collection.CopyTo(Result, 0);
    end;

should become:

    count := collection.Count;
    SetLength(Result, count);
    if count > 0 then
      collection.CopyTo(Result, 0);

to fix the issue. Not sure if there are other ToArray() implementations which suffer the same issue. I'm using Seattle to reproduce this.

Comments (1)

  1. Log in to comment