views:

370

answers:

2

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.

+12  A: 

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)]);
dangph
Elegant solution, thank you.
Fritz Deelman
+3  A: 

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.
Name