Different delegates in loop

Is it possible to have delegates declared in a loop perform different actions?

var buttons = new List<ImageButton>();
buttons.Add(FindViewById<ImageButton>(Resource.Id.button1));
buttons.Add(FindViewById<ImageButton>(Resource.Id.button2));
int count = 1;
foreach(var button in buttons) {
    button.Click += delegate {
        Toast.MakeText(this, "I am " + count, ToastLength.Short).Show();
    }
    count++;
}

The toast message always "I am 2" when clicking either button. Ultimately I would like to have a number of buttons performing slightly different actions when clicked.

Jon Skeet
people
quotationmark

You've got a single count variable, and your anonymous method captures it. That means when the delegate is executed, it will always use the current value of that variable. You want "the value of count when the delegate was created" which means you want a different variable on each iteration. It's simplest to just declare a variable within the loop:

int count = 1;
foreach(var button in buttons) {
    // Each iteration will create a "new" copy variable, whose
    // value never changes
    int copy = count;
    button.Click += delegate {
        Toast.MakeText(this, "I am " + copy, ToastLength.Short).Show();
    }
    count++;
}

people

See more on this question at Stackoverflow