Difference between the System.Array.CopyTo() and System.Array.Clone()

前端 未结 13 2171
攒了一身酷
攒了一身酷 2020-12-02 06:50

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

13条回答
  •  难免孤独
    2020-12-02 07:39

    Array.Clone() would perform technically deep copy, when pass the array of int or string to a method as a reference.

    For example

    int[] numbers = new int[] { -11, 12, -42, 0, 1, 90, 68, 6, -9 }; 
    
    SortByAscending(numbers); // Sort the array in ascending order by clone the numbers array to local new array.
    SortByDescending(numbers); // Same as Ascending order Clone
    

    Even if the methods sort the array of numbers but it wont affect the actual reference passed to the sorting methods.i.e the number array will be in same unsorted initial format in line no 1.

    Note: The Clone should be done in the sorting methods.

提交回复
热议问题