i tried:
int i = 5;
object o1 = i; // boxing the i into object (so it should be a reference type)
object o2 = o1; // set object reference o2 to o1 (so o1 and o2 point to same place at the heap)
o2 = 8; // put 8 to at the place at the heap where o2 points
after running this code, value in o1 is still 5, but i expected 8.
Am I missing something?
That's not how variables in C# work. It has nothing to do with boxing value types.
Consider this:
object o1 = new object();
object o2 = o1;
o2 = new object();
Why would you expect o1
and o2
to contain a reference to the same object? They are the same when you set o2 = o1
, but once you set o2 = new object()
, the value (the memory location pointed to by the variable) of o2
changes.
Maybe what you're trying to do can be done like this:
class Obj {
public int Val;
}
void Main() {
Obj o1 = new Obj();
o1.Val = 5;
Obj o2 = o1;
o2.Val = 8;
}
At the end of Main
, the Val
property of o1
will contain 8
.
To do what you want to do, the value has to be a property of a reference type:
public class IntWrapper
{
public int Value { get; set; }
public IntWrapper(int value) { Value = value; }
}
IntWrapper o1 = new IntWrapper(5);
IntWrapper o2 = o1;
o2.Value = 8;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With