C# Pitfalls

Closures

If you have code like this:

// strings is a list containing the values a, b and c
foreach (string str in strings) {
    Button btn = getButton(str);
    btn.Click += new EventHandler(delegate { MessageBox.Show(str); });
}

The result will be that each button shows a Messagebox with c. Altough one would expect to see a MessageBox with a for the first button. The reason is that the foreach loop gets unrolled into a while loop which has it’s str variable declared outside of the loop. The statement in the loop does not catch the value of the variable but the variable itself. After the foreach loop the value of the variable str is c.

See Blog-Post for details

Leave a comment

Your email address will not be published. Required fields are marked *