Object reference = link string; change to one does not affect the other?

string name = "bob"; object obj = name; obj = "joe"; Console.WriteLine(name); 

I'm a little confused about how the name will print the bob. If the string and the object are reference types, should they not point to the same piece of memory on the heap after assigning "obj = name"? Thanks for any clarification.

Edit: The StackUnderflow example raised 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 class references? Why this does not work the way I can change the class field through one link and it will be reflected in another. Class variables must also be references. Is this where misleading?

+4
source share
4 answers

must not point to the same part of memory on the heap after assigning obj = name

Yes. They both refer to 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 this:

 obj = "joe"; 

You change this so that obj now refers to another line. name will still refer to the original string, however, since you did not reassign it.

If you then do:

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

At this point, it will be wrong.

+6
source

(Since the OP set the background to C ++):

C # links do not match C ++ links; they act more like pointers. In C #, they are not tied to initialization, so the assignment operator ( = ) will assign a new link instead of changing the original object .

In C ++:

 std::string name = "bob"; std::string& obj = name; // now bound to 'name' obj = "joe"; // name is directly affected std::cout << name; // prints "joe" 

In C #:

 string name = "bob"; string obj = name; // both reference "bob" obj = "joe"; // obj now references "joe", and name still references "bob" Console.WriteLine(name); // prints "bob" 
+5
source

No, you just reassign the obj reference to the string object "joe". Strings are immutable, so they cannot be changed in this way. Best of all, you can make wrap name your own class.

 public class MyName { public string Name { get; set; } } MyName firstName = new MyName() { Name = "bob" }; MyName secondName = name; secondName.Name = "joe"; Console.WriteLine(firstName.Name) //outputs "joe" 
+1
source

There is a difference between assignment and action on a variable. If you had this:

 public class A { public string Name; } ... var orig = new A { Name = "bob" }; var obj = orig; obj.Name = "joe"; Console.WriteLine(orig.Name); //"joe" 

Here you should change the object that obj points to (instead of changing what obj points to).

+1
source

All Articles