How to properly use foreach statement? C#

Assets/Scripts/Terraform.cs(48,25): error CS1656: Cannot assign to flo' because it is a foreach iteration variable’

well this is first time I’m trying to use for each as I wanted to write less I even saw it many times but it seems I never Understood exactly how should I use foreach

can someone help me here?

the statement is last 3 lines of code

the last foreach works so what am I missing at before last one? I had to do it with for loop to go forward

float Compare = 0;
		float[] Average = new float[49];
		int WhereX;
		int WhereZ;
		int AvgCount = 0;
		for (int i=-3; i<=3; i++) {
			for (int ii=-3; ii<=3; ii++) {
				Average[AvgCount] = heights[PosX+i, PosZ+ii]-heights[PosX, PosZ];
				AvgCount ++;
				if (Compare < heights[PosX+i, PosZ+ii]){
					Compare = heights[PosX+i, PosZ+ii];
					WhereX = i;
					WhereZ = ii;
				}
			}
		}
		Compare -= heights[PosX, PosZ];
		foreach (float flo in Average) { // doesn't work
			flo = Compare-flo; // doesn't work
		} // doesn't work
            Compare = 0;
		foreach (float flo in Average) { // works
			Compare += flo; // works
		} // works

thanks in advance

You wouldn’t use foreach in that case. Even if it didn’t give you an error message, it wouldn’t work because you’re just writing to a reference value that’s being overwritten.

If you want to change the array items, you have to do a normal loop. I believe this is what you’re trying to do:

for (i = 0; i < Average.Length; i++) {
    Average _= Compare - Average*;*_

}
foreach loops are good when you have a lot of references to an item in the array and you don’t want to keep writing the full reference. But for a small loop like that, a normal for is more than OK.