Search code examples
arraysdelphidelphi-xe

Constant in-place array of strings and records in Delphi


Is something like this possible with Delphi? (with dynamic arrays of strings and records)

type
  TStringArray = array of String;
  TRecArray = array of TMyRecord;

procedure DoSomethingWithStrings(Strings : TStringArray);
procedure DoSomethingWithRecords(Records : TRecArray);
function BuildRecord(const Value : String) : TMyRecord;

DoSomethingWithStrings(['hello', 'world']);
DoSomethingWithRecords([BuildRecord('hello'), BuildRecord('world')]);

I know that it does not compile like that. Just wanted to ask if there's a trick to get something similar to that.


Solution

  • If you don't have to change the length of the arrays inside your DoSomethingWith* routines, I suggest using open arrays instead of dynamic ones, e.g. like this:

    procedure DoSomethingWithStrings(const Strings: array of string);
    var
      i: Integer;
    begin
      for i := Low(Strings) to High(Strings) do
        Writeln(Strings[i]);
    end;
    
    procedure DoSomethingWithRecords(const Records: array of TMyRecord);
    var
      i: Integer;
    begin
      for i := Low(Records) to High(Records) do
        Writeln(Records[i].s);
    end;
    
    procedure Test;
    begin
      DoSomethingWithStrings(['hello', 'world']);
      DoSomethingWithRecords([BuildRecord('hello'), BuildRecord('world')]);
    end;
    

    Please note the array of string in the parameter list - not TStringArray! See the article "Open array parameters and array of const", especially the section about "Confusion", for more information.