[ACCEPTED]-Update Struct in foreach loop in C#-foreach

Accepted answer
Score: 12

More or less what it says, the compiler 6 won't let you change (parts of) the looping 5 var in a foreach.

Simply use:

for(int i = 0; i < things.Count; i+= 1) //  for each file
{
    things[i].Name = "xxx";
}

And it works 4 when Thing is a class because then your looping 3 var is a reference, and you only make changes 2 to the referenced object, not to the reference 1 itself.

Score: 8

A struct is no reference type but a value 7 type.

If you would have a class instead of a struct for 6 Thing, the foreach loop would create a reference 5 variable for you, that would point to the 4 correct element in you list. But since it 3 is a value type, it only operates on a copy 2 of your Thing, which is in this case the iteration 1 variable.

Score: 4

An alternate syntax that I prefer to @Henk's 7 solution is this.

DateTime[] dates = new DateTime[10];

foreach(int index in Enumerable.Range(0, dates.Length))
{
   ref DateTime date = ref dates[index];

   // Do stuff with date.
   // ...
}

If you are doing a reasonable 6 amount of work in the loop then not having 5 to repeat the indexing everywhere is easier 4 on the eye imo.

P.S. DateTime is actually 3 a really poor example as it doesn't have 2 any properties you can set, but you get 1 the picture.

Score: 3

A struct is a value type but a class is 3 a reference type. That's why it compiles 2 when This is a class but not when it is 1 a struct

See more: http://www.albahari.com/valuevsreftypes.aspx

More Related questions