Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TStringlist as function result, minimal code sequence

Tags:

delphi

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?

like image 545
Franz Avatar asked Oct 24 '25 10:10

Franz


1 Answers

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;
like image 181
Uwe Raabe Avatar answered Oct 26 '25 06:10

Uwe Raabe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!