Danny Su
Danny Su

Reputation: 387

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

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

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?

Upvotes: 3

Views: 161

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063298

Your understanding is incorrect; the line

 object p = o;

assigns p the same reference; however:

o = 1;

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

p = 2;

then does the same with yet another boxed object and reference


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

int i = 0;
ref int o = ref i;
ref int p = ref o;

o = 1;
Console.WriteLine(i); // 1
p = 2;
Console.WriteLine(i); // 2

Upvotes: 10

Related Questions