Pass record parameter without declaring it first as a variable

Jason picture Jason · Jan 15, 2012 · Viewed 9.3k times · Source

If I am trying to call a procedure which has a record type (not object) as a parameter, is it possible to somehow pass details of that parameter "inline" without having to declare a variable of that type first?

eg assume I have this simple record type:

type TMyRecord = record
  AString: string;
  AnInt: Integer;
end;

and this procedure declaration:

procedure MyProcedure(Rec: TMyRecord);

If I want to call MyProcedure do I have to declare a variable of type TMyRecord or can I do something like:

MyProcedure(TMyRecord("Test", 10));

That doesn't work (XE2) (get a compiler error about it expecting a ")").

So, can I do something like that? Or not possible.

Thanks

Answer

LU RD picture LU RD · Jan 15, 2012

It is possible using the advanced record structure.

For more information about advanced records, see the Records (advanced) section in Delphi help.

This is a small prototype to see how it works in your case to preinitialize a record in a function/procedure call :

Type
  TRecord = record
   AString : String;
   AnInt : Integer;
   Constructor Create( Const s : String; i : Integer);
  end;

constructor TRecord.Create(const s: String; i: Integer);
begin
  AString := s;
  AnInt := i;
end;

procedure DoSomething( theRec : TRecord);
begin
  WriteLn(theRec.AString, ' ',theRec.AnInt);
end;

begin
  DoSomeThing( TRecord.Create('S',1));
  ReadLn;
end.

Looking at the Delphi RTL, see the definitions of the record types TPoint and TRect in unit system.types (XE2). They define some overloaded Create constructors, which are used in lots of places to preinitialize the record structures in function/procedure calls.