Refresh structure in foreach loop in C #

I have this code (C #):

using System.Collections.Generic; namespace ConsoleApplication1 { public struct Thing { public string Name; } class Program { static void Main(string[] args) { List<Thing> things = new List<Thing>(); foreach (Thing t in things) // for each file { t.Name = "xxx"; } } } } 

It will not compile.
Mistake:

 Cannot modify members of 't' because it is a 'foreach iteration variable' 

If I change Thing to class and not to struct , it compiles.

Please, can someone explain what is happening?

+7
c # foreach
Oct 23 '09 at 10:29
source share
4 answers

In more or less what it says, the compiler will not allow you to modify (parts of) the cyclic var in foreach.

Just use:

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

And it works when Thing is a class, because then your var loop is a link, and you only make changes to the object you are referring to, not the link.

+9
Oct 23 '09 at 10:33
source share

A structure is not a reference type, but a value type.

If you have a class instead of a struct for Thing , the foreach loop will create a reference variable for you that points to the correct item in your list. But since this is a value type, it only works with a copy of your Thing , which in this case is an iteration variable.

+7
Oct 23 '09 at 10:32
source share

A structure is a value type, but a class is a reference type. That's why it compiles when it's a class, but not when it's a structure

More details: http://www.albahari.com/valuevsreftypes.aspx

+2
Oct 23 '09 at 10:34
source share

The alternative syntax that I prefer for @Henk's 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 amount of work in a loop, then no need to repeat indexing everywhere easier on the eyes of imo.

PS DateTime is a really very bad example, since it does not have any properties that you can set, but you get an image.

+1
Nov 29 '17 at 15:53
source share



All Articles