Search code examples
delphiparametersvardelphi-2009anonymous-methods

Is it not possible to use var parameters in a Delphi anonymous method?


Is it not possible to use var parameters in anonymous methods? The following example illustrates (SSCCE) the problem I faced:

program Project2;

{$APPTYPE CONSOLE}

type
  TTextTransformProc = reference to procedure(var AText: string);

procedure WriteTransformedText(const AText: string; AProc: TTextTransformProc);
var
  S: string;
begin
  S := AText;
  AProc(S);
  Writeln(S);
end;

procedure UpperCaseProc(var AText: string);
var
  i: integer;
begin
  for i := 1 to Length(AText) do
    AText[i] := UpCase(AText[i]);
end;

begin
  WriteTransformedText('This is a test.', UpperCaseProc);
  Readln;
end.

The code compiles, but when run I get an access violation error (and no upper-case string). If I remove reference to, the code works as expected.


Solution

  • This is a compiler defect. Your code is correct. The compiler is wrong. Until you can get a more modern compiler you'll have to find a work around.