Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object reference = string reference; change to one doesn't affect the other?

Tags:

c#

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?

like image 912
user943870 Avatar asked Aug 05 '26 21:08

user943870


1 Answers

shouldn't they point to the same piece of memory on the heap after the "obj = name" assignment

Yes. They both reference the same string instance. You can see this by calling:

bool sameStringReference = object.ReferenceEquals(obj, name); // Will be true

However, as soon as you do:

obj = "joe";

You're changing this so that obj is now referencing a different string. name will still be referencing the original string, however, as you haven't reassigned it.

If you then do:

sameStringReference = object.ReferenceEquals(obj, name); // Will be false

This will be false at this point.

like image 118
Reed Copsey Avatar answered Aug 07 '26 17:08

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!