Search code examples
c#.netvariable-assignmentreference-type

Reference question: when are two objects equal?


I have a Vector class, and I was testing the following unit test (using nUnit).

1  Vector test1 = new Vector(new double[] { 6, 3, 4, 5 });
2  Vector test2 = test1;
3  Assert.AreEqual(test1, test2, "Reference test");
4  test2 = new Vector(new double[] { 3, 3, 4, 5 });
5  Assert.AreEqual(test1, test2, "Reference test");

The first test in line 3 passes, but the second test in line 5 fails. Shouldn't test2 also point to the same memory as test1, since I did the assignment statement in line 2? My Vector is defined as a class, so it is a reference type. On the other hand, the following tests pass:

1  Vector test1 = new Vector(new double[] { 6, 3, 4, 5 });
2  Vector test2 = test1;
3  Assert.AreEqual(test1, test2, "Reference test");
4  test2[1] = 4;
5  Assert.AreEqual(test1, test2, "Reference test");

Does that mean that, when I use the new operator to define a new object, old assignments are no longer valid? Any other (or correct - if I am wrong) explanation?


Solution

  • The line

    test2 = new Vector(new double[] { 3, 3, 4, 5 });
    

    creates a new instance of Vector on the heap and assigns its address to the test2 variable. test2 will point to a new, completely distinct object after that.

    In contrast, the line

    test2[1] = 4;
    

    does not change the test2 variable itself (which is a reference to some object on the heap). Rather, it's changing the object it points to. test2 still refers to the same location on the heap.

    To summarize, in the former, you are changing the reference while in the latter, you are altering the referent.