Anonymous Methods in Delphi






4.25/5 (3 votes)
An introduction to anonymous methods in Delphi
Introduction
Under the scope of Delphi, an anonymous method is either a procedure or function that’s unattached to an identifier. In other words, anonymous methods don’t have names, which is why they are called “anonymous”.
Basically, you can assign a block of code (in the form of a procedure or function) directly to a variable.
I am going to give you a simplistic example. I am going to Keep it simple, Stupid! to avoid distracting you with any complexity.
This is the wording of the task: create a console application which prints
“Hello world
” and “Good bye
” to the standard output. Constraint: Use the
Writeln
function just once in the code.
To accomplish such reckless task in the old days (before the introduction of anonymous methods), you could do this:
program Project1;
{$APPTYPE CONSOLE}
procedure PrintString(aText: string);
begin
Writeln(aText);
end;
begin
PrintString('Hello world');
PrintString('Good bye');
Readln;
end.
How to do the same with anonymous methods? Take a look at the following code:
{$APPTYPE CONSOLE}
type
TMyAnonymousProcedureType = reference to procedure(aText: string);
var
A: TMyAnonymousProcedureType;
begin
A:= procedure(aText: string) //No semicolon here
begin
Writeln(aText);
end;
A('Hello world');
A('Good bye');
Readln;
end.
As you can see in the example above, we have assigned code directly to the
variable A
. Then, we called A
with parameters, and voilà!: we have
accomplished our reckless task with anonymous methods as well.
Pay attention to this: if you are tented to declare variable A like this:
var
A: reference to procedure(aText: string);
Don’t! That shortcut doesn’t work. You’ll get a compilation error… like this:
Undeclared identifier: ‘reference’
So, you do need to declare:type
TMyAnonymousProcedureType = reference to procedure(aText: string);
Only later, you can define the type of variable A
.
You might be asking by now: why to bother with all this? What's the benefit? Well, in the previous example there’s little or no benefit present.
Generally speaking, anonymous methods are handy in the following cases:
- You have been trying to name a local method for hours. You
cannot think of a name for it. Well, think no more: use
anonymous methods. Don’t put a tasteless name like
Foo()
,XXX()
,Aux()
, etc. - You create a function that is called just once (it’s just called from one spot).
- You can use anonymous methods to provide elegant and
simpler implementations.
This is the case when combining generics types with
anonymous methods for example. I should write about this
shortly. Subscribe to my feed and stay tuned
With this post, I wanted to introduce anonymous methods to you. It’s OK if
you don’t see the benefits clearly right now. You’ll get there.