B
Brad Williams
I'm trying to get clearer on limitations of assignment/modifications within
a foreach. Why does the following gives a compilation error if MyType is a
struct, but it does not if MyType is a class?
public struct MyType // change to class, and it compiles clean
{
public int f;
}
public void foo()
{
MyType[] a = new MyType[3];
for (int n = 0; n < 3; n++)
a[n] = new MyType();
foreach (MyType c in a)
{
c.f = 77; // compilation error: The left-hand side of assignment
must be a variable, property or indexer
this.WriteLine(c.f.ToString());
}
}
a foreach. Why does the following gives a compilation error if MyType is a
struct, but it does not if MyType is a class?
public struct MyType // change to class, and it compiles clean
{
public int f;
}
public void foo()
{
MyType[] a = new MyType[3];
for (int n = 0; n < 3; n++)
a[n] = new MyType();
foreach (MyType c in a)
{
c.f = 77; // compilation error: The left-hand side of assignment
must be a variable, property or indexer
this.WriteLine(c.f.ToString());
}
}