473,387 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Delegate is using the wrong value

(Sorry if this is a double post)

Hi Guys,

I am creating a delegate a couple times and passing in a local
variable. However, when the delegate is invoked it uses the variable
passed into the last created instance (sorry that was a mouthful).
Here is an example from my code:

private void dlgFavorites_Load(object sender, EventArgs e)
{
Hashtable bookmarks =
ConfigurationSettings.GetConfig("Bookmarks") as Hashtable;

if(bookmarks == null)
return;

int i = 0;
foreach (DictionaryEntry pair in bookmarks)
{
Button btn = new Button();
btn.DialogResult = DialogResult.OK;
btn.Text = (string)pair.Key;

btn.Click += new EventHandler(delegate
{
m_selectedUrl = (string)pair.Value;
});
btn.Dock = DockStyle.Fill;

tableLayoutPanel1.Controls.Add(btn, i%2, (int)(i/2));

++i;
}
}

I was able to get around the problem by doing:

string value = (string)pair.Value;
btn.Click += new EventHandler(delegate
{
m_selectedUrl = value;
});

So I think it has something to do with boxing ValueTypes. Anyway I
would love to hear any ideas.

Thanks,
James

Apr 11 '07 #1
2 1528
james wrote:
I am creating a delegate a couple times and passing in a local
variable. However, when the delegate is invoked it uses the variable
passed into the last created instance (sorry that was a mouthful).
foreach (DictionaryEntry pair in bookmarks)
There is a single variable called 'pair', and its value changes as the
loop progresses. In particular, it doesn't create a new variable once
per iteration. This is important when the semantics of anonymous
delegate variable capture are considered.
{
Button btn = new Button();
btn.DialogResult = DialogResult.OK;
btn.Text = (string)pair.Key;

btn.Click += new EventHandler(delegate
{
m_selectedUrl = (string)pair.Value;
Here, you have captured the variable called 'pair'. That means that when
this delegate gets executed, it reads the value that is currently in
pair, whatever it is.

And because this Click event presumably won't be executed until much
later, after this loop has finished executing, it will have the value of
the last item in the loop.

And since all Click events refer to the same variable 'pair', they'll
all refer to the same value, its final value.
});
btn.Dock = DockStyle.Fill;
string value = (string)pair.Value;
This creates a new variable that is local to the loop and is created
fresh and new each time around the loop.
btn.Click += new EventHandler(delegate
{
m_selectedUrl = value;
});

So I think it has something to do with boxing ValueTypes. Anyway I
would love to hear any ideas.
No, it doesn't have to do with boxing, but with variable capture. It's
important to know that anonymous delegates capture variables, not
values.

-- Barry

--
http://barrkel.blogspot.com/
Apr 11 '07 #2
Great answer. Thanks a lot Barry.

-James

Apr 12 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Jon Davis | last post by:
If two delegates are created that point to the exact same method, and an event is assigned both delegates, ... myObj.MyEvent += new EventHandler(MyHandler); myObj.MyEvent += new...
4
by: CJ Taylor | last post by:
What does this mean? This method creates delegates for static methods only. An instance method is a method that is associated with an instance of a class; a static method is a method that is...
4
by: ^MisterJingo^ | last post by:
Hi all, I've been trying to get my head around delegates. The book i'm using had a single example, not much explaination, and didn't show how to set up a delegate and pass variables in and out...
7
by: Ant | last post by:
Hello, Very simple question but one I need clarified. Which part of the statement below is considered the 'delegate'? Is it the 'new System.EventHandler' or the btnAccept_Click? or is it...
11
by: matsi.inc | last post by:
I am looking to make something like a delegate that i can use in my projects but am having a hard time getting started. The behavior I am most interested in is how a delegate changes it's Invoke...
3
by: james | last post by:
Hi guys, I create a delegate and pass in a local variable. When the variable is a reference type everything works fine, but when it is a valuetype the delegate uses the value of the last...
26
by: raylopez99 | last post by:
Here is a good example that shows generic delegate types. Read this through and you'll have an excellent understanding of how to use these types. You might say that the combination of the generic...
7
by: Stefan Hoffmann | last post by:
hi @all, is there something like an anonymous delegate? This is the original code: -- private delegate void DelegateSetFormCaption(string text); private void SetFormCaption(string text) {
10
by: vcquestions | last post by:
Hi. Is there way to have a function pointer to a delegate in c++/cli that would allow me to pass delegates with the same signatures as parameters to a method? I'm working with managed code. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.