0

Please consider the following code:

public class Program {

    public struct A 
    {
        public int Prop {get;set;}
    }

    public static void Main()
    {
        var obj = new A();
        obj.Prop = 10;

        var list = new List<A>(){obj};
        foreach(var l in list) {
            l.Prop = 20; //here I'm getting compile time error "Cannot modify members of 'l' because it is a 'foreach iteration variable'"
        }
    }
}

So my question is: why struct properties cannot be assigned while iterating over a list of structs? Please note that even when iterating with simple for like this:

for (int i=0; i<list.Count(); ++i)
    list[i].Prop  = 20;

I'm still getting compile time error...

Grigoryants Artem
  • 1,401
  • 2
  • 15
  • 32
  • About that for loop. You'll need to create a copy of a struct. See: [Changing the value of an element in a list of structs](https://stackoverflow.com/questions/51526/changing-the-value-of-an-element-in-a-list-of-structs) – default locale Nov 29 '19 at 11:26

1 Answers1

0

You cannot modify collection over which you are iterating with foreach.

Instead you should use for loop, which allows that:

for(int i = 0; i < list.Length; i++)
{
  list[i].Prop = 200;
}

You can refer to this question: Why can't we assign a foreach iteration variable, whereas we can completely modify it with an accessor?

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69