Wednesday, October 1, 2008

Boxing and arrays

There is one more catch with boxing (see also my former post Boxing and explicit conversions). Consider the code

public struct X
{
   public string Value { get; set; }
}

public void Fun()
{
   X x1 = new X { Value="original string 1" };
   X x2 = new X { Value="original string 2" };
   X[] array = new X[] { x1, x2 };

   array[0].Value = "modified string";
   //! x1 is not changed
}


I am occasionally amazed that x1 has "original string 1" on the line marked '!' although array[0] reads "modified string". Hell yes, that is because of boxing again. If X was classx1 would be changed, too.

No comments: