Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Record constructors in delphi

Is it possible to use records as a method parameter, and call it without implicitly declaring an instance of said record?

I would like to be able to write code like this.

type
  TRRec = record
    ident : string;
    classtype : TClass;
  end;

procedure Foo(AClasses : array of TRRec);

then calling the method like this or something similar.

Foo([('Button1', TButton), ('Lable1', TLabel)]);

I'm still stuck on Delphi 5 by the way.

like image 578
Fritz Deelman Avatar asked Mar 05 '09 12:03

Fritz Deelman


2 Answers

Yes. Almost.

type
  TRRec = record
    ident : string;
    classtype : TClass;
  end;

function r(i: string; c: TClass): TRRec;
begin
  result.ident     := i;
  result.classtype := c;
end;

procedure Foo(AClasses : array of TRRec);
begin
  ;
end;

// ...
Foo([r('Button1', TButton), r('Lable1', TLabel)]);
like image 171
dan-gph Avatar answered Oct 18 '22 21:10

dan-gph


It is also possible to work with a const array, but it isn't so flexible as the solution given by "gangph": (especially that you have to give the size ([0..1]) of the array in the array declaration. The records are anomymous, the array isn't).

type
  TRRec = record
    ident : string;
    classtype : TClass;
  end;

procedure Foo(AClasses : array of TRRec);
begin
end;

const tt: array [0..1] of TRRec = ((ident:'Button1'; classtype:TButton),
                                   (ident:'Lable1'; classtype:TLabel));

Begin
  Foo(tt);
end.
like image 44
Name Avatar answered Oct 18 '22 23:10

Name