If I have:
var myObjects = new ConcurrentBag<object>();
And try to remove objects via:
foreach (var myObject in myObjects.ToArray())
{
myObjects.TryTake(out myObject);
}
The compiler complains with: “Readonly local variable cannot be used as an assignment target”
Yet, if I add a local reference within the foreach it compiles:
foreach (var myObject in myObjects.ToArray())
{
var localReference = myObject;
myObjects.TryTake(out localReference);
}
What exactly is going on here?
The iteration variable in a
foreach(i.e.myObject) cannot be assigned a new value inside theforeach. It is not allowed.In the first scenario, the
outtries to do this. In the second scenario, you *never try to reassign tomyObject, so it is fine.To quote from the ECMA specification, 15.8.4, emphasis mine: