Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Lets start out with a silly but illustrative example:</p> <pre><code>Object o = 15; o = "apples"; </code></pre> <p>At no point do we get the impression that we just turned the number 15 into a string of apples. We know that <code>o</code> is simply a pointer. Now lets do this in iterator form.</p> <pre><code>int[] nums = { 15, 16, 17 }; foreach (Object o in nums) { o = "apples"; } </code></pre> <p>Again, this really accomplishes nothing. Or at least it <em>would</em> accomplish nothing were it to compile. It certainly wouldn't insert our string into the int array -- that's not allowed, and we know that <code>o</code> is just a pointer anyway.</p> <p>Let's take your example:</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>Were this to compile, the <code>Location</code> in your example stars out referring to a value in <code>Map</code>, but then you change it to refer to a new <code>Position</code> (implicitly created by the addition operator). Functionally it's equivalent to this (which DOES compile):</p> <pre><code>foreach (Position Location in Map) { //We want to fudge the position to hide the exact coordinates Position Location2 = Location + Random(); //No more Error Plot(Location2); } </code></pre> <p>So, why does Microsoft prohibit you from re-assigning the pointer used for iteration? Clarity for one thing -- you don't want people assigning to it thinking they've changed your position within the loop. Ease of implementation for another: The variable might hide some internal logic indicating the state of the loop in progress. </p> <p>But more importantly, there is no reason for you to <em>want</em> to assign to it. It represents the current element of the looping sequence. Assigning a value to it breaks the "Single Responsibility Principle" or <a href="http://www.codinghorror.com/blog/archives/000805.html" rel="nofollow noreferrer">Curly's Law</a> if you follow Coding Horror. A variable should mean one thing only.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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