Search This Blog

Tuesday, July 11, 2023

Anonymouse methods in Delphi

In Delphi, the term "anonymous methods" refers to a programming feature that allows you to define and use inline functions without explicitly declaring them as separate named functions or procedures. Anonymous methods are also known as anonymous functions or lambda expressions.

Anonymous methods provide a convenient way to write encapsulated blocks of code that can be passed as parameters to other routines or assigned to variables. They are commonly used in event handling, multithreading, and callback scenarios.

Here's an example of how anonymous methods can be used in Delphi:


program AnonymousMethodsDemo;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TMathOperation = reference to function(a, b: Integer): Integer;

function PerformMathOperation(a, b: Integer; mathOp: TMathOperation): Integer;
begin
  Result := mathOp(a, b);
end;

procedure ExecuteAnonymousMethodDemo;
var
  addResult: Integer;
  subtractResult: Integer;
begin
  // Example: Performing addition using an anonymous method
  addResult := PerformMathOperation(10, 5,
    function(a, b: Integer): Integer
    begin
      Result := a + b;
    end
  );

  // Example: Performing subtraction using an anonymous method
  subtractResult := PerformMathOperation(10, 5,
    function(a, b: Integer): Integer
    begin
      Result := a - b;
    end
  );

  WriteLn('Addition Result: ', addResult);
  WriteLn('Subtraction Result: ', subtractResult);
end;

begin
  try
    ExecuteAnonymousMethodDemo;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  ReadLn;
end.

In the above example, we define a TMathOperation type which represents an anonymous method that takes two integers as parameters and returns an integer. The PerformMathOperation function accepts two integers and a TMathOperation instance and executes the specified math operation.

The ExecuteAnonymousMethodDemo procedure demonstrates two examples of using anonymous methods. It performs addition and subtraction operations by passing the required logic as an anonymous method to the PerformMathOperation function.

When executed, the program outputs the results of the addition and subtraction operations using anonymous methods.

Note that Delphi doesn't have native support for anonymous functions, but it supports anonymous methods through the reference to syntax as shown in the code.

No comments:

Post a Comment