Change in structure after boxing

I have the following code:

//Interface defining a Change method
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); // "(1, 1)"

        p.Change(2, 2);
        Console.WriteLine(p); // "(2, 2)"

        Object o = p;
        Console.WriteLine(o); // "(2, 2)"

        ((Point)o).Change(3, 3);
        Console.WriteLine(o); // "(2, 2)"

        //Boxes p, changes the boxed object and discards it
        ((IChangeBoxedPoint)p).Change(4, 4);
        Console.WriteLine(p); // "(2, 2)"

        IChangeBoxedPoint h = ((IChangeBoxedPoint)p);
        h.Change(4, 4);
        //Boxed p is not yet garbage collected
        Console.WriteLine(p);// "(2, 2)"

        Console.WriteLine(h); //"(4, 4)" //After this line boxed p is garbage collected

        //Changes the boxed object and shows it
        ((IChangeBoxedPoint)o).Change(5, 5);
        Console.WriteLine(o); // "(5, 5)"

        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 , .

+4
2

, *, . , , .

, , . p h . h p .

# , , , , , . , . , .

*) @KirillShlenskiy , , . , .

+3

, , . , , :

- , . # .

, , , .

+2

Source: https://habr.com/ru/post/1546391/


All Articles