1

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);
    }
}
3
  • 1
    by default, all parameters are passed by value regardless whether it's a reference type of value type. Commented Oct 7, 2017 at 14:33
  • 1
    arrays are reference types. for arrays that means that if you pass the array to another function you can change the content of the array from that function. But you can't assign another array, for that you would need ref Commented Oct 7, 2017 at 14:36
  • I understand. Thank you very much. Commented Oct 7, 2017 at 14:36

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.