Why reference point to different values?

Viewed 38

Can someone explain why this code outputs 5? I thought that packaging is happening here, the value is wrapped in an object and sent to the heap. And the reference stays on the stack. And then x and y will point to the same address on the heap. But it is not.

object x = 5;
object y = x;
x = 10;
Console.WriteLine(y);
1 Answers

What you're doing is the same as

int x = 5;
int y = x; // copy value from x to y: y = 5
x = 10; // set x to 10, y is unchanged: y = 5
Console.WriteLine(y)
// outputs: 5

This is the same as with reference types.

class A
{
    public int Data { get; set; }
    public A(int i) { Data = i; }
    public override string ToString() { return Data.ToString(); }
}

object x = new A(5);
object y = x; // y is reference to x' object
> x = new A(10); // x is now pointing to a new object, y is unchanged
Console.WriteLine(y)
// outputs: 5
Related