user7066088
user7066088

Reputation:

Need some clarification about reference type's behavior

I have read the Difference between a Value Type and a Reference Type, in this article, the author is saying:

Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value

Based on the above quote, I expected the following code which will assigning a reference variable to another, doesn't copy the data but it is indeed copying the data as well. Would you please help me to understand this?

Class1 i1 = new Class1();
i1.Name = "Name1";
Class1 i2 = i1;
//i2.Name is "Name1"

For i2 I expected it refers to the same location of the heap as the i1 value that is right, but based on the article the data should not be copied. Also my question is not deserve to be marked as duplicate because I know about the difference between value and reference type, I just need some clarification about reference types and what's the usage of deep copy/clone/shallow, if we can simply use assignment?

Upvotes: 0

Views: 76

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56423

For i2 I expected it refers to the same location of the heap as the i1 value that is right

Correct, they refer to the same location in memory.

but based on the article the data should not be copied.

Correct again, the data is not copied, let's get some illustration together:

             _ _ _ _
            |       |
 i1  - - - -| addr  |
            |_ _ _ _|

Now, when you do Class1 i2 = i1; you're essentially copying the reference of i1 and assigning it to i2 which you can visualise as:

             _ _ _ _
            |       |
 i1  - - - -| addr  |
            |_ _ _ _|
          /
         /               
        /     
   i2  /

hence i1.Name and i2.Name have the same name because both i1 and i2 refer to the same object in memory.

Upvotes: 2

Wanton
Wanton

Reputation: 840

Reference is just a pointer to a object. Doing that just copies reference. If you do i2.Name = "foobar"; i1.Name will also change to foobar.

Upvotes: 0

Related Questions