Re: Anonymous Methods scope question
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Wed, 12 Sep 2007 20:33:06 +0100
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
.
- References:
- Anonymous Methods scope question
- From: Gabe Moothart
- Anonymous Methods scope question
- Prev by Date: Re: Anonymous Methods scope question
- Next by Date: Re: Turning a Word Document into a Blob
- Previous by thread: Anonymous Methods scope question
- Next by thread: RE: Anonymous Methods scope question
- Index(es):
Relevant Pages
|