Here's your code:
foreach (string item in sArray)
{
item = "Some assignment.\r\n";
}
Here's a rough approximation of what the compiler does with this:
using (var enumerator = sArray.GetEnumerator())
{
string item;
while (enumerator.MoveNext())
{
item = enumerator.Current;
// Your code gets put here
}
}
The IEnumerator<T>.Current
property is read-only, but that's not actually relevant here, as you are attempting to assign the local item
variable 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 a for
loop instead of a foreach
:
for (int i = 0; i < sArray.Length; ++i)
{
sArray[i] = "Some assignment.\r\n";
}