Cannot assign to 's' because it is a 'foreach iteration variable'

  • Thread starter Thread starter bg_ie
  • Start date Start date
B

bg_ie

Hi,

What is wrong with the following -

short[] arrfile = new short[100];

foreach (short s in arrfile)
{
s = 10;
}

Error 1 Cannot assign to 's' because it is a 'foreach iteration
variable'

Thanks,

Barry.
 
Exactly what it says.

The language does not allow you to reassign a "foreach" variable. Even
if you could, it wouldn't update the contents of hte array. What do
you want to do here? If you want to change the values in the array,
then you will have to do somehing like:

for(int i = 0 ; i < arrfile.Length; i++) {
arrfile = 10;
}

Marc
 
Good point Marc.. Thanks

Hi,

from MSDN:
"This error occurs when an assignment to variable occurs in a read-
only context. Read-only contexts include foreach iteration variables,
using variables, and fixed variables. To resolve this error, avoid
assignments to a statement variable in using blocks, foreach
statements, and fixed statements."

The foreach keyword just enumerates IEnumerable instances (getting an
IEnumerator instances by calling the GetEnumerator() method).
IEnumerator is read-only, therefore values can't be changed using
IEnumerator => can't be changed using the foreach context.

Hope this helps.
Moty
 
Hi,

from MSDN:
"This error occurs when an assignment to variable occurs in a read-
only context. Read-only contexts include foreach iteration variables,
using variables, and fixed variables. To resolve this error, avoid
assignments to a statement variable in using blocks, foreach
statements, and fixed statements."

The foreach keyword just enumerates IEnumerable instances (getting an
IEnumerator instances by calling the GetEnumerator() method).
IEnumerator is read-only, therefore values can't be changed using
IEnumerator => can't be changed using the foreach context.

Hope this helps.
Moty

This is the IEnumerator problem I've faced. I guess this is a typical
case where we need to go for 'for' loop instead of 'foreach'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top