Search code examples
c#.netforeach

Update Struct 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 won't compile.
The error is:

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

If I change Thing to a class rather than a struct, however, it does compile.

Please can someone explain what's going on?


Solution

  • More or less what it says, the compiler won't let you change (parts of) the looping 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 when Thing is a class because then your looping var is a reference, and you only make changes to the referenced object, not to the reference itself.