dou dou - 4 months ago 8
Java Question

Error while convertiong enhanced for loop with java to c#

I try to have this enhanced for loop of a Java code in my C# code:

for (float value : array) {
if (Float.isInfinite(value) || Float.isNaN(value)) {
value = 0;
}
}


I tried this out:

foreach (float value in array)

{

if (float.IsInfinity(value) || float.IsNaN(value))
{
value = 0;
}
}


But I have this error that told me I have not the right to modify value because it is an iteration variable.

Answer

You need to use a normal for loop if you want to update the iterator variable:

for(int i = 0 ; i < array.Length; i++)
{

    if (float.IsInfinity(array[i]) || float.IsNaN(array[i]))
    {
        array[i] = 0;
    }
}

From C# specifications:

During execution of a foreach statement, the iteration variable represents the collection element for which an iteration is currently being performed. A compile-time error occurs if the embedded statement attempts to modify the iteration variable (via assignment or the ++ and -- operators) or pass the iteration variable as a ref or out parameter.

Comments