» Help

How to use a function or a procedure as a parameter to another function

   
  1. Declare the function (or procedure) that will be used as a parameter. In the example below, this is TFunctionParameter.
  2. Define a function that will accept another function as a parameter. In the example below this is DynamicFunction.
type
  TFunctionParameter = function(const value: integer): string;

// ...

function One(const value: integer): string;
begin
  result:= IntToStr(value);
end;

function Two(const value: integer): string;
begin
  result:= IntToStr(2 * value);
end;

function DynamicFunction(f: TFunctionParameter): string;
begin
  result:= f(2006);
end;

Example usage:

var
  s: string;
begin
  s := DynamicFunction(One) ;
  ShowMessage(s) ; //will display "2006"

  s := DynamicFunction(Two) ;
  ShowMessage(s) ; // will display "4012"
end;
Author: Shlomo Abuisak
Contributor: Shlomo Abuisak
Added: 2009-11-05
Last updated: 2009-11-05

« Return to contents »