Hello,
In one of my asp.net applications, I create a series of checkboxes, set
their properties, and give them an "onChecked" event handler on the fly
using an anonymous method. The code looks like this:
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<Guid, stringdataHash = ... //db access
foreach(KeyValuePair<Guid, stringrow in dataHash)
{
CheckBox cb = new CheckBox();
cb.ID = row.Key.ToString();
cb.Text = row.Value;
cb.AutoPostBack = true;
//mark the checkbox checked/unchecked
cb.Checked = ...
cb.CheckedChanged += delegate( object sender, EventArgs e )
{
if (cb.Checked) {
... //save state
}
else {
... //save state
}
};
//add this checkbox to the page
PlaceHolder1.Controls.Add( cb );
PlaceHolder1.Controls.Add( new HtmlGenericControl( "br" ) );
} //foreach
} //PageLoad
I've coded this up, and it seems to work. But upon further reflection,
I'm not sure why. Notice that I reference the local variable cb inside
the anonymous event handler. I know that anonymous methods have access
to their enclosing scope, which is why I can do that. But the scope that
they have access to is updated by every loop iteration, isn't it? And
shouldn't that change the object that cb points to?
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.
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?
Thanks,
Gabe 2 2139
Gabe Moothart <gm*******@gmail.comwrote:
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 - <sk***@pobox.com> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
>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.
[This is true if you declare CheckBox cb = null; before the foreach block]
"Gabe Moothart" wrote:
Hello,
In one of my asp.net applications, I create a series of checkboxes, set
their properties, and give them an "onChecked" event handler on the fly
using an anonymous method. The code looks like this:
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<Guid, stringdataHash = ... //db access
foreach(KeyValuePair<Guid, stringrow in dataHash)
{
CheckBox cb = new CheckBox();
cb.ID = row.Key.ToString();
cb.Text = row.Value;
cb.AutoPostBack = true;
//mark the checkbox checked/unchecked
cb.Checked = ...
cb.CheckedChanged += delegate( object sender, EventArgs e )
{
if (cb.Checked) {
... //save state
}
else {
... //save state
}
};
//add this checkbox to the page
PlaceHolder1.Controls.Add( cb );
PlaceHolder1.Controls.Add( new HtmlGenericControl( "br" ) );
} //foreach
} //PageLoad
I've coded this up, and it seems to work. But upon further reflection,
I'm not sure why. Notice that I reference the local variable cb inside
the anonymous event handler. I know that anonymous methods have access
to their enclosing scope, which is why I can do that. But the scope that
they have access to is updated by every loop iteration, isn't it? And
shouldn't that change the object that cb points to?
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.
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?
Thanks,
Gabe This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Nick Coghlan |
last post by:
GvR has commented that he want to get rid of the lambda keyword for Python 3.0.
Getting rid of lambda seems like a worthy goal, but I'd prefer to see it dropped
in favour of a different syntax,...
|
by: Cordell Lawrence |
last post by:
Okay guys,
We are wondering if this is a bug in Framework 2.0.40607 and
looking for some clarification on the issue. Take a look at the folowing
code.
public delegate bool BoundryTest(int...
|
by: John Smith |
last post by:
I really can not appreciate why Microsoft has introduced Anonymous
methods. It promotes quick and dirty style of programming and as I can
see it offers no advantages over normal methods.
I have...
|
by: rickeringill |
last post by:
Hi comp.lang.javascript,
I'm throwing this in for discussion. First up I don't claim to be any
sort of authority on the ecmascript language spec - in fact I'm a
relative newb to these more...
|
by: Jon Slaughter |
last post by:
I was wondering if maybe allowing "fields" for methods. The reason is to
encapsulate the data that is mainly used by the method and to prevent the
need of having to create new variables every time...
|
by: Frankie |
last post by:
I have just gotten up to speed on what anonymous methods are (syntax,
capabilities, etc), and how they can be used with /called via delegates.
What I am wondering is...
1. Are they only/mostly...
|
by: Tony |
last post by:
Hello!
Here I have some text from a book I read. It says:
"An interesting point to note concerning anonymous methods is that they are
effectively local to the code
block that contains them, and...
|
by: Peter Duniho |
last post by:
On Mon, 01 Sep 2008 16:14:10 -0700, Blip <blip@krumpli.comwrote:
Briefly, an anonymous method is exactly that: a method without a name.
When you use the "delegate" keyword to declare an...
|
by: Peter |
last post by:
Hi
I've been delving into "delegates" and "anonymous methods", and now
I've come across the term "closure".
Some information I've found says that C# does not have closures, other
information...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
|
by: ryjfgjl |
last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
| |