C# Value and Reference types

前端 未结 6 1277
灰色年华
灰色年华 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:32

    That's actually how reference types works.

    As you said, byte[] is a reference type like all other arrays. Let's analyze your sample line by line;

    byte[] a = { 1, 2, 3, 4 };
    

    --> You created a byte array in memory and a is a reference that array.

    enter image description here

    byte[] b = a;
    

    --> Your b is referencing the same object with a which is { 1, 2, 3, 4 } but they are different references.

    enter image description here

    a = null;
    

    --> Your a is not referencing anywhere in the memory but that doesn't effect b.

    enter image description here

提交回复
热议问题