C# Value and Reference types

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

    Your question makes the assumption that when you make the assignment:

    byte[] b = a;
    

    And that you're making some sort of graph association like so:

    b -> a -> { 1, 2, 3, 4 }
    

    And when you make the assignment of a to null, you impact the value of b, because:

    b -> a -> null
    

    But that's not how copying references work. When you copy the reference, you really make a copy of the reference that a has, like so:

    a ----> { 1, 2, 3, 4 }
                  ^
    b ------------|
    

    This is why when you make the assignment of a to null, you don't impact the value of b, just a:

    a ----> null      { 1, 2, 3, 4 }
                              ^
    b ------------------------|
    

提交回复
热议问题