TStringlist as function result, minimal code sequence

How to return a Stringlist from a function has been discussed many time before.
My code sequence version 1 is just a recap how to do it.

function GetStrings : TStringList;
begin
  Result := TStringList.Create;
  Result.Add('string A');
  Result.Add('string B');
end;

procedure TForm1.Button1Click(Sender: TObject);
var stemp : tStringList;
begin
  stemp := GetStrings;
  MyListBox.items.addstrings(stemp);
  stemp.Free;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  MyListBox.items.addstrings(GetStrings);
end;

is there any option to fix the memory leak in version2 with "no extra code", how dangerous is this approach at all, will this cause any failures if my stringlist is just a few string items, out of memory issues will not happen?

>Solution :

Don’t use a TStringList as result type, but a TArray<string>. Of course this makes version1 obsolete.

function GetStrings : TArray<string>;
begin
  var lst := TStringList.Create;
  try
    lst.Add('string A');
    lst.Add('string B');
    Result := lst.ToStringArray;
  finally
    lst.Free;
  end;
end;

Leave a Reply