Anonymous Methods

An anonymous method is used to is used to define an inline callbacks that is assignable to a Blocks, an interface reference with a single method that can act as a delegate, or an Expression tree.

Anonymous methods start with the block, delegate or method keyword, followed by a Method signature and a begin/end block that includes one or more Statements.

Anonymous methods can use any member defined in the scope they are defined in. Any change done to variables in the local scope will affect the lambda and vice versa.

method Loop(aAction: block(aValue: Integer));
begin
  for i: Integer := 0 to 10 do
    aAction(i);
end;

method Test;
begin
  Loop(method(a: Integer); begin
    writeLn(a)
  end); // This prints "0" thru "10"
end;

An alternative syntax for defining anonymous methods is a Lambda expression, which is shorter but cannot provide parameter types and relies on type inference.

See Also