I have a problem with an anonymous method within a loop.
The following code is just to illustrate my problem:
private void Form1_Load(object sender, EventArgs e)
{
List<string> bassists = new List<string>(){
"Jaco Pastorius",
"Marcus Miller",
"Flea",
"Vicor Wooten"
};
foreach (string item in bassists)
{
this.button1.Click += (s, ea) => Output(s, ea, item);
}
}
private void Output(object s, EventArgs e, string item)
{
this.listBox1.Items.Add(item);
}
And when I click into the button, the output is:
Victor Wooten
Victor Wooten
Victor Wooten
Victor Wooten
instead of:
Jaco Pastorius
Marcus Miller
Flea
Vicor Wooten
The main point of my problem is the differents execution context. I know my example is stupid.