I had this code :
foreach (object obj in _Destinations)
{
obj = _ItemsSource;
}
which was generating the error
Cannot assign to ‘obj’ because it is a ‘foreach iteration variable’
So I “circled” the problem with the following code :
for (int i = 0; i < _Destinations.Count; i++)
{
_Destinations[i] = _ItemsSource;
}
This works on my actual cases but I’m not sure that this is the exact same thing for any type of object. Is that the case ?
EDIT : _Destinations is a List<object>
This is definitely not the same exact thing: for starters, the second one works, while the first one does not 🙂
The reason the first snippet does not work is because it uses an iterator from the
_Distancelist, and it is not possible to assign to the original collection throughIEnumerable<T>‘s iterator. The second snippet uses[index]to access the underlying list or array. This construct allows reading and writing; that’s why it works.As far as accessing all elements of the list or array in the same order is concerned, both constructs are identical.