Home > Net >  Why is an array passed without ref, changed by CopyTo inside the method?
Why is an array passed without ref, changed by CopyTo inside the method?

Time:10-07

As the array parameter is passed without ref-keyword, this code outputs initial value of array (i.e. 1...6):

using System;
using System.Linq;

class Program 
{
    static void Main(string[] args) 
    {
        var arr = new int[] {1, 2, 3, 4, 5, 6};

        Rotate(arr, 3);
        
        Console.WriteLine(string.Join(',', arr));
    }

    static void Rotate(int[] nums, int k)
    {
        var tail = nums.TakeLast(k).ToArray();
        nums = tail.Concat(nums)
            .Take(nums.Length)
            .ToArray();
    }
}

It is obvious, because inside the Rotate method there is it's own array with values, copied from the parameter values. And if I want to change arr values in the calling method, I need to pass it to the Rotate method by ref, it works. But I don't understand, why if replace assignment with CopyTo() method the parameter behaves as like it is passed by reference:

static void Rotate(int[] nums, int k)
{
    var tail = nums.TakeLast(k).ToArray();

    tail.Concat(nums)
        .Take(nums.Length)
        .ToArray()
        .CopyTo(nums, 0);
}

CodePudding user response:

Because CopyTo() sets the elements inside the array and does not reassign the array variable itself.

.ToArray() creates a new object while CopyTo() modifies it. The latter gets passed a reference to an existing array.

See also enter image description here

  • Related