C# Value and Reference types

前端 未结 6 1257
灰色年华
灰色年华 2021-01-06 15:55

Please see the following lines of code mentioned below:

byte[] a = { 1, 2, 3, 4 };
byte[] b = a; // b will have all values of a.
a = null; 

6条回答
  •  时光取名叫无心
    2021-01-06 16:20

    When a type is a value type, it means that the variables of this type store the actual data. When a type is a reference type, it means that the variables of this type store a reference to the actual data.

    In both cases, assignment from one variable to another copies the content of the variable. For value types, this means that the value is copied from one variable to the other, duplicating the actual data and thus creating a new object. For reference types, this means that the reference is copied from one variable to the other, duplicating the reference but leaving the actual data intact. To stress that: the object isn't copied, but the reference is. The two copies of the reference are independent, even though it's easy to observe that they point to the same object when dereferenced.

    From these you can easily see that the assignment from one variable to the other copies the reference to the byte array, so you have two references to the byte array. Afterwards, when you assign null to one of the variables, you are copying a null reference to it, overwriting the original reference (which was stored in that variable) to the byte array. So, now you don't have two references to the byte array, but only one again - the object is the same, but the references to it are independent.

    (Similarly, if you reassign the byte array back to the nulled variable, it doesn't mean that all variables in your program that pointed to null will point to the byte array - only the one you assigned will.)

提交回复
热议问题