1 Answer
1

When you have a function like the one in the question, where you have an anonymous method accessing a local variable, Delphi appears to create one TInterfacedObject descendant that captures all the stack based variables as it's own public variables. Using Barry's trick to get to the implementing TObject and a bit of RTTI we can see this whole thing in action.

Of course this code doesn't compile. I'm magic-less :-) But the idea here is that an "Magic" object is created behind the scenes and local variables that are referenced from the anonymous method are transformed in public fields of the magic object. That object is uses as an interface (IUnkown) so it gets reference-counted. Apparently the same object captures all used variables AND defines all the anonymous methods.

This should answer both "When" and "How".

Here's the code I used to investigate. Put a TButton on a blank form, this should be the whole unit. When you press the button you'll see the following on screen, in sequence:

000000 (bogus number)

000000 (the same number): This proofs both anonymous methods are actually implemented as methods of the same object!