Using Local Variables

We could have achieved the same effect using method pointers albeit with a different and less readable syntax. What makes anonymous method clearly different is the way they can refer to local variables of the calling method. Consider the following code:

procedure TFormAnonymFirst.btnLoca1Va1C1ick(

Sender: TObject); var aNumber: Integer; begi n aNumber := 0; Ca11Twice (10, procedure (n: Integer) begi n

Memo1.Lines.Add (IntToStr (aNumber)); end;

Here the method, still passed to the Ca11Twice procedure, uses the local parameter n, but also a local variable from the context from which it was called, aNumber. What's the effect? The two calls of the anonymous method will modify the local variable, adding the parameter to it, 10 the first time and 11 the second. The final value of aNumber will be 21.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment