MinhKiyo
MinhKiyo

Reputation: 311

Why cannot resize array by other function?

According to MSDN, if all arrays are reference type, then why in the given sample code, to change the size of the array must to use the keyword ref? Thank you!

class Program
{
    static void Main(string[] args)
    {
        int[] test1 = { 1, 2, 3, 4 };
        ResizeArray1(test1);
        Console.WriteLine("Size 1 new = " + test1.Length);  // Size 1 new = 4 ??

        int[] test2 = { 1, 2, 3, 4 };
        ResizeArray2(ref test2);
        Console.WriteLine("Size 2 new = " + test2.Length);  // Size 2 new = 8

        Console.ReadKey();
    }

    static void ResizeArray1(int[] arr)
    {
        Array.Resize(ref arr, 8);
    }

    static void ResizeArray2(ref int[] arr)
    {
        Array.Resize(ref arr, 8);
    }
}

Upvotes: 1

Views: 93

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56473

if all arrays are reference type, then why in the given sample code, to change the size of the array must to use the keyword ref?

Simply, because Array.Resize allocates a new array. It then copies existing element values to the new array. so to make sure changes affect the argument that was first passed into Array.Resize we must use ref. This is also because, by default, all parameters are passed by value regardless whether it's a reference type of value type.

Upvotes: 4

Related Questions