Variable binding

Top  Previous  Next

New features since Delphi 7 > Anonymous Methods > Variable binding

 

There is a subtle difference between anonymous methods and lambda expressions: while anonymous methods extend the lifetime of captured references, this is not the case for lambda expressions. In the following Delphi code snippet the anonymous method, which is assigned to the variable adder, binds the value 20 to the parameter variable y.The lifetime of y is extended in Delphi, until adder is destroyed.

 

 

type

  TFuncOfInt = reference to function(x: Integer): Integer;

 

function MakeAdder(y: Integer): TFuncOfInt;

begin

Result := function(x: Integer) : Integer

  begin

    Result := x + y;

    end;

end;

 

procedure TestAnonymous1; 

var

  adder: TFuncOfInt;

begin

  adder := MakeAdder(20);

  Writeln(adder(22)); 

end;

 

->

 

public delegate int TFuncOfInt(int x);

 

public static void TestAnonymous1()

{

  TFuncOfInt adder = null;

  adder = MakeAdder(20);

  Writeln(adder(22));

}

 

public static TFuncOfInt MakeAdder(int Y)

{

  TFuncOfInt result = null;

  result = delegate(int x)

  {

    int result_1 = 0;

    result_1 = x + Y;

    return result_1;

  };

  return result;

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 



This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content