Why are assignment operators (=) invalid in a foreach loop? I’m using C#, but I would assume that the argument is the same for other languages that support foreach (e.g. PHP). For example, if I do something like this:
string[] sArray = new string[5];
foreach (string item in sArray)
{
item = "Some assignment.\r\n";
}
I get an error, “Cannot assign to ‘item’ because it is a ‘foreach iteration variable’.”
Here’s your code:
Here’s a rough approximation of what the compiler does with this:
The
IEnumerator<T>.Currentproperty is read-only, but that’s not actually relevant here, as you are attempting to assign the localitemvariable to a new value. The compile-time check preventing you from doing so is in place basically to protect you from doing something that isn’t going to work like you expect (i.e., changing a local variable and having no effect on the underlying collection/sequence).If you want to modify the internals of an indexed collection such as a
string[]while enumerating, the traditional way is to use aforloop instead of aforeach: