Re: Anonymous Methods scope question

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Gabe Moothart <gmoothart@xxxxxxxxx> wrote:
Essentially I think that, when these anonymous event handlers are
invoked, their copy of cb should always be a reference to the _last_
CheckBox created - because they have a reference, not a copy, of their
containing scope.

No - local variables have gained the concept of an "instance".
Basically, each time you go round the loop, you're redeclaring cb and
creating a new "instance" of the variable. It's that "instance" that is
captured by the anonymous method.

It gets more confusing when you access some variables from an inner
scope and some variables from an outer scope. Note that the variable
declared in a "foreach" loop only has a single instance for the whole
loop.

So, my questions are:
1) Why does this work?
2) Is this a safe pattern for adding event handlers? Is it likely to
bite me in the future?

Shouldn't do in this case - but you need to be clear as to what's going
on.

--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.



Relevant Pages

  • Re: general performance question
    ... (It seems to me that the JVM should be free to null out the reference once it goes out of scope, or even if it's in scope but flow analysis makes it clear that it can't be used any more, but that was a minority opinion.) ... If you create an Object in a loop and then reassign another Object to the same reference in the loop, the first Object is eligible for garbage collection. ...
    (comp.lang.java.programmer)
  • Re: general performance question
    ... first Object is eligible for garbage collection. ... For a loop, the value set in the last iteration also leaks the ... How can it if the reference is created in the block? ... The method's stack frame isn't collected until the method exits; it has no notion of block scope. ...
    (comp.lang.java.programmer)
  • Re: general performance question
    ... first Object is eligible for garbage collection. ... For a loop, the value set in the last iteration also leaks the ... How can it if the reference is created in the block? ... no notion of block scope. ...
    (comp.lang.java.programmer)
  • Re: References, AddressOf and Object management
    ... So when you loop, this is like leaving a scope then re-entering? ... >> Does reference 'a' only get assigned first time around the loop and, ... > return a smart pointer to the new object. ...
    (comp.lang.cpp)
  • Re: vbs output to txt file
    ... the reference count to that object will be decremented. ... As does going out of scope:) ... You are religiously setting objects to nothing and not ... and so am seriously lacking in both scripting expertise ...
    (microsoft.public.scripting.wsh)