Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify a foreach iteration variable from within foreach loop?

When I try to do this...

Item[,] array = new Item[w, h];  // Two dimensional array of class Item, 
                                 //   w, h are unknown at compile time.
foreach(var item in array)
{
    item = new Item();
}

...I get Cannot assign to 'item' because it is a 'foreach iteration variable'.

Still, I'd like to do that.

The idea is to assign default Item class values to existing item.

like image 399
user1306322 Avatar asked Aug 04 '12 17:08

user1306322


People also ask

Can you change a foreach loop?

Instead, changes are simply discarded at the end of each loop cycle. As a result we cannot modify the collection we loop over (Stephens, 2014). To prevent confusion with the foreach loop, don't bother with changing the loop variable inside the loop.

What is VAR in foreach loop?

The variable var is local to the foreach loop; if a variable outside the loop has the same name, it is unaffected by the foreach loop. In fact, var is optional; if you don't specify a variable in the foreach statement, the special variable $_ can be used inside the loop to represent the values in list.

Which is correct syntax for foreach loop?

It is necessary to enclose the statements of foreach loop in curly braces {}. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.


2 Answers

Okay, now that we know your aim instead of how you were trying to achieve it, it's much easier to answer your question: you shouldn't be using a foreach loop. foreach is about reading items from a collection - not changing the contents of a collection. It's a good job that the C# compiler makes the iteration variable read-only, otherwise it would have let you change the value of the variable without that actually changing the collection. (There'd have to be more significant changes to allow changes to be reflected...)

I suspect you just want:

for (int i = 0; i < array.GetLength(0); i++)
{
    for (int j = 0; j < array.GetLength(1); j++)
    {
        array[i, j] = new Item();
    }
}

That's assuming it's a rectangular array (an Item[,]). If it's an Item[][] then it's an array of arrays, and you'd handle that slightly differently - quite possibly with a foreach for the outer iteration:

foreach (var subarray in array)
{
    for (int i = 0; i < subarray.Length; i++)
    {
        subarray[i] = new Item();
    }
}
like image 63
Jon Skeet Avatar answered Sep 18 '22 10:09

Jon Skeet


Not knowing the size isn't a problem:

for (int i = 0; i < twoDimArray.GetLength(0); i++)
{
    for (int j = 0; j < twoDimArray.GetLength(1); j++)
    {
        twoDimArray[i, j] = ...
    }
}
like image 25
Joe Shanahan Avatar answered Sep 18 '22 10:09

Joe Shanahan