Why can't we assign a foreach iteration variable, whereas we can completely modify it with an accessor?

C#ForeachIterationAccessor

C# Problem Overview


I was just curious about this: the following code will not compile, because we cannot modify a foreach iteration variable:

        foreach (var item in MyObjectList)
        {
            item = Value;
        }

But the following will compile and run:

        foreach (var item in MyObjectList)
        {
            item.Value = Value;
        }

Why is the first invalid, whereas the second can do the same underneath (I was searching for the correct english expression for this, but I don't remember it. Under the...? ^^ )

C# Solutions


Solution 1 - C#

foreach is a read only iterator that iterates dynamically classes that implement IEnumerable, each cycle in foreach will call the IEnumerable to get the next item, the item you have is a read only reference, you can not re-assign it, but simply calling item.Value is accessing it and assigning some value to a read/write attribute yet still the reference of item a read only reference.

Solution 2 - C#

The second isn't doing the same thing at all. It's not changing the value of the item variable - it's changing a property of the object to which that value refers. These two would only be equivalent if item is a mutable value type - in which case you should change that anyway, as mutable value types are evil. (They behave in all kinds of ways which the unwary developer may not expect.)

It's the same as this:

private readonly StringBuilder builder = new StringBuilder();

// Later...
builder = null; // Not allowed - you can't change the *variable*

// Allowed - changes the contents of the *object* to which the value
// of builder refers.
builder.Append("Foo");

See my article on references and values for more information.

Solution 3 - C#

You can't modify a collection while it's being enumerated. The second example only updates a property of the object, which is entirely different.

Use a for loop if you need to add/remove/modify elements in a collection:

for (int i = 0; i < MyObjectList.Count; i++)
{
    MyObjectList[i] = new MyObject();
}

Solution 4 - C#

If you look at the language specification you can see why this is not working:

The specs say that a foreach is expanded to the following code:

 E e = ((C)(x)).GetEnumerator();
   try {
      V v;
      while (e.MoveNext()) {
         v = (V)(T)e.Current;
                  embedded-statement
      }
   }
   finally {
      … // Dispose e
   }

As you can see the current element is used to call MoveNext() on. So if you change the current element the code is 'lost' and can't iterate over the collection. So changing the element to something else doesn't make any sense if you see what code the compiler is actually producing.

Solution 5 - C#

It would be possible to make item mutable. We could change the way the code is produced so that:

foreach (var item in MyObjectList)
{
  item = Value;
}

Became equivalent to:

using(var enumerator = MyObjectList.GetEnumerator())
{
  while(enumerator.MoveNext())
  {
    var item = enumerator.Current;
    item = Value;
  }
}

And it would then compile. It would not however affect the collection.

And there's the rub. The code:

foreach (var item in MyObjectList)
{
  item = Value;
}

Has two reasonable ways for a human to think about it. One is that item is just a place-holder and changing it is no different to changing item in:

for(int item = 0; item < 100; item++)
    item *= 2; //perfectly valid

The other is that changing item would actually change the collection.

In the former case, we can just assign item to another variable, and then play with that, so there's no loss. In the latter case this is both prohibited (or at least, you can't expect to alter a collection while iterating through it, though it doesn't have to be enforced by all enumerators) and in many cases impossible to provide (depending on the nature of the enumerable).

Even if we considered the former case to be the "correct" implementation, the fact that it could be reasonably interpreted by humans in two different ways is a good enough reason to avoid allowing it, especially considering we can easily work around that in any case.

Solution 6 - C#

Because the first one doesn't make much sense, basically. The variable item is controlled by the iterator (set on each iteration). You shouldn't need to change it- just use another variable:

foreach (var item in MyObjectList)
{
    var someOtherItem = Value;

    ....
}

As for the second, there are valid use cases there- you might want to iterate over an enumeration of cars and call .Drive() on each one, or set car.gasTank = full;

Solution 7 - C#

The point is that you cannot modify the collection itself while iterating over it. It is absolutely legal and common to modify the objects the iterator yields.

Solution 8 - C#

Because the two are not the same. When doing the first, you might expect to change the value that is in the collection. But the way foreach works, there is no way that could have been done. It can only retrieve items from the collection, not set them.

But once you have the item, it's an object like any other and you can modify it in any (allowed) way you can.

Solution 9 - C#

Use for loop instead of foreach loop and assign value. it will work

foreach (var a in FixValue)
{
    for (int i = 0; i < str.Count(); i++)
    {
       if (a.Value.Contains(str[i]))
           str[i] = a.Key;
    }
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGianT971View Question on Stackoverflow
Solution 1 - C#Mohamed AbedView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#James JohnsonView Answer on Stackoverflow
Solution 4 - C#Wouter de KortView Answer on Stackoverflow
Solution 5 - C#Jon HannaView Answer on Stackoverflow
Solution 6 - C#Chris ShainView Answer on Stackoverflow
Solution 7 - C#Florian GreinacherView Answer on Stackoverflow
Solution 8 - C#svickView Answer on Stackoverflow
Solution 9 - C#SPnLView Answer on Stackoverflow