Reputation: 934
Im trying to iterate of a two dimensional array of Buttons like this
Button[,] buttonsArray = new Button[row,col];
foreach(Button button in buttonsArray)
{
button = new Button();
}
but im getting the next error: "Error Cannot assign to 'button' because it is a 'foreach iteration variable'"
what im doing worng?
Upvotes: 1
Views: 130
Reputation: 16636
You cannot modify the value of the variable in a foreach
loop. To circumvent this, you should use a regular for
loop:
for(int i = row; i < row; i++)
{
for(int j = col; j < col; j++)
{
buttonsArray[i, j] = new Button();
}
}
Upvotes: 1
Reputation: 1500873
The compiler message says it all - you're trying to assign a new value to button
, but the iteration variable (the one declared by a foreach
statement) is read-only. A foreach
loop can only be used to iterate over the existing content in a collection - it can't be used to change the content in a collection. (Note that if you change the data within an object referred to by the collection, that's not actually changing the value in the collection, which would just be a reference to the object.)
I suspect you really want something more like this:
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
buttonsArray[i, j] = new Button();
}
}
Upvotes: 3