I have the following code:
internal interface IChangeBoxedPoint
{
void Change(Int32 x, Int32 y);
}
internal struct Point : IChangeBoxedPoint
{
private Int32 m_x, m_y;
public Point(Int32 x, Int32 y)
{
m_x = x;
m_y = y;
}
public void Change(Int32 x, Int32 y)
{
m_x = x; m_y = y;
}
public override string ToString()
{
return String.Format("({0}, {1})", m_x.ToString(), m_y.ToString());
}
}
public class Program
{
static void Main(string[] args)
{
Point p = new Point(1, 1);
Console.WriteLine(p);
p.Change(2, 2);
Console.WriteLine(p);
Object o = p;
Console.WriteLine(o);
((Point)o).Change(3, 3);
Console.WriteLine(o);
((IChangeBoxedPoint)p).Change(4, 4);
Console.WriteLine(p);
IChangeBoxedPoint h = ((IChangeBoxedPoint)p);
h.Change(4, 4);
Console.WriteLine(p);
Console.WriteLine(h);
((IChangeBoxedPoint)o).Change(5, 5);
Console.WriteLine(o);
Console.Read();
}
}
This is a modified CLR example via C # 4th ed (pg 138). The book says that
((IChangeBoxedPoint)p).Change(4, 4);
Console.WriteLine(p); // "(2, 2)"
will output "(2, 2)" because garbage will be immediately collected in box p. However, wouldn't the actual reason for this be that changing the value of a variable in a box only changes the value in the object on the heap, in which case leaving p untouched? Why does the garbage collector in the box have anything to do with this?
I believe that this has nothing to do with it, because in this code:
IChangeBoxedPoint h = ((IChangeBoxedPoint)p);
h.Change(4, 4);
//Boxed p is not yet garbage collected
Console.WriteLine(p);// "(2, 2)"
Console.WriteLine(h); // //After this line boxed p is garbage collected
we box p by invoking the change method on box p, keeping h alive by using it in Console.WriteLine(h);, however Console.WriteLine(p);it will still output "(2, 2)".
- , , , p , .