Search code examples
delphirecordopen-array-parameters

Passing constants to a function parameter that is an open array of record


I have a record defined like this:

TRec = record
  S: string;
  I: Integer;
end;

I can initialize a constant of this record type like this:

const
  Rec: TRec = (S:'Test'; I:123);

Now I have a function that takes an open array of this record type:

function Test(AParams: array of TRec);

Can I call this function using similar syntax as the constant declaration?

Test([(S:'S1'; I:1), (S:'S2'; I:2)]);

This does not work. Should I use something else?


Solution

  • Add a constructor to the record type, which takes the parameters needed.

    TRec = record
      s : string;
      i : integer;
      constructor create( s_ : string; i_: integer );
    end;
    
    constructor TRec.create( s_ : string; i_: integer );
    begin
      s := s_;
      i := i_;
    end;
    
    procedure test( recs_ : array of TRec );
    var
      i : Integer;
      rec : TRec;
    begin
      for i := 0 to high(recs_) do
        rec := recs_[i];
    end;
    
    procedure TForm1.Button1Click( sender_ : TObject );
    begin
      test( [TRec.create('1',1), TRec.create('2',2)] );
    end;
    

    As Remy Lebeau reflected, it works just with Delphi 2006 or newer versions. If you have an older IDE you should create an utility class with a method (along with other methods) witch conforms to the record constructor above:

    TRecUtility = class
      public
        class function createRecord( s_ : string; i_: integer ) : TRec;
        //... other utility methods
    end;
    
    procedure foo;
    begin
      test( [TRecUtility.createRec('1',1), TRec.createRec('2',2)] ); 
    end;