Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is The Iteration Variable in a C# foreach statement read-only?
    text
    copied!<p>As I understand it, C#'s foreach iteration variable is immutable.</p> <p>Which means I can't modify the iterator like this:</p> <pre><code>foreach (Position Location in Map) { //We want to fudge the position to hide the exact coordinates Location = Location + Random(); //Compiler Error Plot(Location); } </code></pre> <p>I can't modify the iterator variable directly and instead, I have to use a for loop</p> <pre><code>for (int i = 0; i &lt; Map.Count; i++) { Position Location = Map[i]; Location = Location + Random(); Plot(Location); i = Location; } </code></pre> <p>Coming from a C++ background, I see foreach as an alternative to the for loop. But with the above restriction, I usually fallback to using the for loop. </p> <p>I'm curious, what is the rationale behind making the iterator immutable? </p> <hr> <p>Edit: </p> <p>This question is more of a curiousity question and not as a coding question. I appreciated the coding answers but I can't mark them as answers.</p> <p>Also, the example above was over-simplified. Here is a C++ example of what I want to do:</p> <pre><code>// The game's rules: // - The "Laser Of Death (tm)" moves around the game board from the // start area (index 0) until the end area (index BoardSize) // - If the Laser hits a teleporter, destroy that teleporter on the // board and move the Laser to the square where the teleporter // points to // - If the Laser hits a player, deal 15 damage and stop the laser. for (int i = 0; i &lt; BoardSize; i++) { if (GetItem(Board[i]) == Teleporter) { TeleportSquare = GetTeleportSquare(Board[i]); SetItem(Board[i], FreeSpace); i = TeleportSquare; } if (GetItem(Board[i]) == Player) { Player.Life -= 15; break; } } </code></pre> <p>I can't do the above in C#'s foreach because the iterator i is immutable. I think (correct me if I'm wrong), this is specific to the design of foreach in languages.</p> <p>I'm interested in why the foreach iterator is immutable.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload