I want to create some Box
objects inside an array. In the begining I initialized these objects in a for-loop, attaching also an event handler which passes the current index i
.
int[] boxes = new int[9];
for (int i = 0; i < boxes.Length; i++)
{
var b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(i, e.Marking);
boxes[i] = b;
}
private void OnBoxMarkOccupied(int position, Marking marking)
{
BoxOccupiedEvent?.Invoke(this, new BoxMarkingEventArgs(position, marking));
}
I am expecting that when MarkingOccupiedEvent
of boxes[0]
is raised then I am going to retrieve a position equals to 0 from BoxMarkingEventArgs
. All I am getting though is the value of 9. And this applies to all boxes inside the array, not just the first one.
Out of curiosity I deleted the code in the loop and wrote the initialization code by hand (since it's only 9 boxes),
var b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(0, e.Marking);
boxes[0] = b;
b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(1, e.Marking);
boxes[1] = b;
b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(2, e.Marking);
boxes[2] = b;
b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(3, e.Marking);
boxes[3] = b;
b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(4, e.Marking);
boxes[4] = b;
b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(5, e.Marking);
boxes[5] = b;
b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(6, e.Marking);
boxes[6] = b;
b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(7, e.Marking);
boxes[7] = b;
b = new Box();
b.MarkingOccupiedEvent += (s, e) => OnBoxMarkOccupied(8, e.Marking);
boxes[8] = b;
Guess what, that code works!
What is wrong with the approach using the for-loop?