Boxing/unboxing, changing the copy of the refence of the boxed value does not refected to the boxed value

Dan*_* Su 1 c# boxing unboxing types reference

So I read through the documentation of Microsoft here.

Consider the following code:

int i = 0;
object o = i;
object p = o;

o = 1;
p = 2;

Console.WriteLine($"o:{o}, p:{p}");
//output o:1, p:2
Run Code Online (Sandbox Code Playgroud)

My understanding is that boxing happen on object o = i;, now o is a refence to the value in heap. Then p is assigned to be same as o.

Why isn't the change of p refected to o? Aren't they pointing to the same address?

Mar*_*ell 6

Your understanding is incorrect; the line

 object p = o;
Run Code Online (Sandbox Code Playgroud)

assigns p the same reference; however:

o = 1;
Run Code Online (Sandbox Code Playgroud)

creates a new object (boxed integer) and assigns the new reference to o; o and p are now different references;

p = 2;
Run Code Online (Sandbox Code Playgroud)

then does the same with yet another boxed object and reference


Your expectation is how "ref locals" work, however:

 object p = o;
Run Code Online (Sandbox Code Playgroud)