Let's start with stupid but illustrative examples:
Object o = 15; o = "apples";
In no case does it seem that we just turned number 15 into a chain of apples. We know that o is just a pointer. Now let's do it in the form of an iterator.
int[] nums = { 15, 16, 17 }; foreach (Object o in nums) { o = "apples"; }
Again, this does nothing. Or, at least, he could not compile anything. This, of course, will not inject our string into the int array - it is not allowed, and we know that o is just a pointer.
Take your example:
foreach (Position Location in Map) {
If this is compiled, Location in your example will display with a reference to the value in Map , but then you will change it to refer to the new Position (implicitly created by the add statement). Functionally, it is equivalent to this (which compiles):
foreach (Position Location in Map) {
So why does Microsoft forbid you to rewrite the pointer used for iteration? Clarity for one thing - you do not want people to appoint him, thinking that they have changed your position in the cycle. Ease of implementation for another: a variable can hide some internal logic indicating the state of the current loop.
But more importantly, there is no reason why you want to assign it. It represents the current element of the sequence of loops. Assigning a value to it violates the "principle of single responsibility" or Curly Law if you follow Coding Horror. A variable should mean only one thing.
tylerl Apr 23 '09 at 3:22 2009-04-23 03:22
source share