Friday, April 25, 2008

Delphi put by ref properties

In Delphi 6 and earlier there was a an unintended compiler feature, put by ref properties. It allowed properties to be passed by references. Here is an example:


function GetCount: Integer;
procedure SetCount(var Value: Integer);

property Count: Integer read GetCount write SetCount;

It was decided that the setter property by reference wasn't safe so starting with Delphi 7 this became a compiler error. But this is a requirement for COM so the compiler option {$VARPROPSETTER ON} was introduced to enable the put by ref behavior. At the top of each _TLB.pas file generated you will see this compiler directive.

4 comments:

Anonymous said...

You can still use the const keyword in the setter... Does that pass it by reference?

Anonymous said...

CONSTs are only passed by reference if it is beneficial to do so (f.ex. ShortString, AnsiString, RECORDs larger than 4 bytes, SETs, etc).

Simple variables (BYTE/INTEGER etc.) are passed by value for CONST parameters, but are prevented by the compiler from being modified from within the PROCEDURE or FUNCTION.

Jolyon Smith said...

Hmm, it's not clear whether the COM requirement is for "var" params per se or simply more reliable "by reference" passing.

If the latter then it might have been clearer to create a new "byref" keyword, since it meets a different set of requirements of either "const" (by reference if possible) or "var" (by reference and modifiable).

Now, where did I put my time machine...?

:)

Chris Bensen said...

Jolyn,

When possible we use existing Delphi language features rather than adding a new one. It's better for everyone in the long run.

Post a Comment