string name = "bob";
object obj = name;
obj = "joe";
Console.WriteLine(name);
I’m a bit confused on how name will print bob. If string and object are both reference types, shouldn’t they point to the same piece of memory on the heap after the “obj = name” assignment? Thanks for any clarification.
Edit: StackUnderflow’s example brought up another related question.
MyClass myClass1 = new MyClass();
MyClass myClass2;
myClass1.value = 4;
myClass2 = myClass1;
myClass2.value = 5; // myClass1 and myClass2 both have 5 for value
What happens when both are class references? Why does it not work the same way, as I can
change a class field via one reference and it is reflected in the other. Class variables should also be references. Is that where stings being immutable comes into play?
Yes. They both reference the same string instance. You can see this by calling:
However, as soon as you do:
You’re changing this so that
objis now referencing a different string.namewill still be referencing the original string, however, as you haven’t reassigned it.If you then do:
This will be false at this point.