Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Struct in foreach loop in C#

Tags:

c#

.net

foreach

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?

like image 543
AJ. Avatar asked Oct 23 '09 10:10

AJ.


1 Answers

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

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

like image 132
armannvg Avatar answered Oct 03 '22 13:10

armannvg