Fun with Closures in C# 2.0
One of my favorite features in C# 2.0 are the anonymous delegates. Your code starts to almost look like ruby :). But hold on, they can be tricky.
Can you find the bug here?
Button[] digits = new Button[] {Zero, One, Two, Three}; for (int i = 0; i
——
Give up?
After executing this code, clicking any button would result in this ClickDigit being called with the value of 4 instead of the appropriate value between 0 and 3.
——
I groaned when I realized what it was. ClickDigit gets called with i in the state it is in when the button gets clicked – not when the event handler was attached.
Once you realize this, it’s very simple to fix it, even if it looks kind of strange.
So it should be :
Button[] digits = new Button[] {Zero, One, Two, Three}; for (int i = 0; i
Tags: c#