The following code prints (when invoking MyMethod):
0
0
0
1
I would expect it to print:
0
0
1
1
Why is this?
Code:
private struct MyStruct
{
public MyInnerStruct innerStruct;
}
private struct MyInnerStruct
{
public int counter;
public void AddOne()
{
++counter;
}
}
public static void MyMethod()
{
MyStruct[] myStructs = new MyStruct[] { new MyStruct() };
foreach (var myStruct in myStructs)
{
MyStruct myStructCopy = myStruct;
Console.WriteLine(myStruct.innerStruct.counter);
Console.WriteLine(myStructCopy.innerStruct.counter);
myStruct.innerStruct.AddOne();
myStructCopy.innerStruct.AddOne();
Console.WriteLine(myStruct.innerStruct.counter);
Console.WriteLine(myStructCopy.innerStruct.counter);
}
}