Nested Struct Bug??

  • Thread starter Thread starter Rene
  • Start date Start date
R

Rene

Please help me, add a button to a new for and copy and paste the simple code
below. According to me, the last message box in the Click event of the
button should popup a "123" but instead it pops up a "0". Why?? Is this a
bug?? Thank you.

---------------- CODE TO COPY ----------------

public struct struct1
{
public int a;
public struct2 b;
}

public struct struct2
{
public int x;
}

private void button1_Click(object sender, System.EventArgs e)
{
struct1[] arrayWithStructs = new struct1[1];
struct2 s2 = arrayWithStructs[0].b;
s2.x = 123;

MessageBox.Show(s2.x.ToString()); // Good.
MessageBox.Show(arrayWithStructs[0].b.x.ToString()); // Bad
}
 
Rene said:
Please help me, add a button to a new for and copy and paste the simple code
below. According to me, the last message box in the Click event of the
button should popup a "123" but instead it pops up a "0". Why?? Is this a
bug?? Thank you.

It's not a bug - it's because structs are value types. When you do

struct s2 = ...;

you're creating a new copy of the value which is then completely
separate from the array.
 
Got it, thank you.


Jon Skeet said:
It's not a bug - it's because structs are value types. When you do

struct s2 = ...;

you're creating a new copy of the value which is then completely
separate from the array.
 
Back
Top