Default Parameter Value for TSomething in Delphi

I would like to know if this is possible in Delphi (or if there is a clean path around it):

type TSomething = record X, Y : Integer; end; 

GetSomething( x, y ) Returns a record with these values.

... and then you have this function with the TSomething parameter as the parameter, and you want to use it as the default

 function Foo( Something : TSomething = GetSomething( 1, 3 ); 

The compiler spits out an error here, but I'm not sure if it has a way!

Can this be done?

+4
source share
4 answers

The easiest way is to use overloaded procedures:

 program TestOverloading; {$APPTYPE CONSOLE} uses SysUtils; type TSomething = record X,Y : integer; end; const cDefaultSomething : TSomething = (X:100; Y:200); procedure Foo(aSomething : TSomething); overload; begin writeln('X:',aSomething.X); writeln('Y:',aSomething.Y); end; procedure Foo; overload; begin Foo(cDefaultSomething); end; begin Foo; readln; end. 
+3
source

Use overload:

 procedure Foo(const ASomething: TSomething); overload; begin // do something with ASomething end; procedure Foo; overload; begin Foo(GetSomething(1, 3)); end; 
+10
source

Use a class instead of writing, and something like this:

 TSomething = class public X: integer; Y: integer end; procedure Foo(Something: TSomething = nil); begin if (Something = nil) then Something := GetSomething(1, 3); ... end; 
+3
source

If you use a pointer instead of a record type, you can use nil as the default:

 type TSomething = record X, Y : Integer; end; PSomething = ^TSomething; function Foo(Something: PSomething = nil); 

In fact, passing pointers as parameters is usually faster, since it avoids copying memory blocks.

0
source

All Articles