Link to home
Start Free TrialLog in
Avatar of ricbrad
ricbrad

asked on

Is there a shorthand syntax to create a record?

I need to pass a record as an argument to a function, and I have all the record fields as seperate variables. Is there an easy way to do this?

At the moment I am writing:

---

procedure SomeProc;
var
   x, y  : integer;
   pt    : TPoint;
begin
  <---  get x and y somehow --->
  pt.x := x;
  pt.y := y;
  somePointFunction(pt);
end;

---

I'd quite like to be able to write something more like:

---

somePointFunction(TPoint(x: x; y: y));

---

but that doesn't compile.

Of course, it's not too much bother when the record has just two fields, but if it is a long record it can work out as a lot of code.

Thanks for your time,


Rich
ASKER CERTIFIED SOLUTION
Avatar of LRHGuy
LRHGuy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Evarest
Evarest

And for TPoint itself, you can simply call

MyFunction(Point(X,Y));

Evarest
Shorthand? Nope, not unless you write one yourself. There are some shorthand methods for some Windows API records like Point for a point and Rect for a rect. But in general, assignments of fields in records are just one field at the time. Like LRHGuy just told you...

In general, when you do need to fill some record structure quite often, write a shorthand function for it. Again, LRHGuy gave the example.

There is, however, some other trick that you might in Delphi 5 and higher, which is called function overloading. Means you can have a function somePointFunction that accepts just a TPoint record and a second function with the same make that accepts two fields from a record. Something like:

procedure somePointFunction(Pt:TPoint); overload;
Procedure somePointFunction(X, Y: Integer); overload;

I tend to use overloaded functions quite regular this way, just letting one method fill a record, then call the other. Like this:

procedure somePointFunction(Pt:TPoint); overload;
begin
  somePointFunction(Pt.X, Pt.Y)
end;

Or this:

Procedure somePointFunction(X, Y: Integer); overload;
var Pt: TPoint;
begin
  Pt.X := X;
  Pt.Y := Y;
  somePointFunction(Pt);
end;

Don't use both at the same time, though. You'd end up in an endless loop. ;-)
Sometimes your code becomes much easier by using method overloading, although it does have some limitations too. (For example, the compiler must be able to determine which overloaded method you're calling and can only do this if both methods have different parameter types. But it does allow you to write:

  somePointFunction(x; y);