C# array parameter reference

This question already has an answer here:

  • Passing Objects By Reference or Value in C# 7 answers

  • The array is passed by a reference, you can see this by doing A[0] = 7; from inside another method.

    That reference (held by the outer variable A ), however is passed by value to the function. The reference is copied and a new variable is created and passed to the function. The variable outside the function is not affected by the reassignment to the parameter variable A inside the function.

    To update the original variable you need to use the ref keyword so the parameter inside the function represents the same object as outside of the function.

    int[] A = new int[] {1, 2, 3};
    fun2(A);
    // A at this point says 7, 2, 3.
    fun(ref A);
    // A at this point says 4, 5, 6.
    
    void fun2(int[] a)
    {
       a[0] = 7;
    }
    
    void fun(ref int[] a)
    {
       int[] B = new int[] {4, 5, 6};
       a = B;
    }
    

    I thought all arrays are passed by reference in C#

    Actually ( the reference of the original array object is passed by value ) which is the usual behavior in case of reference types in C#.

    Your understanding is partially correct, the reference is passed but is passed by value which means a new reference gets created which is pointing to the original array object A .

    The fun(int[] A) has it's own copy of reference which is pointing to the array object which contains 1,2,3 and in the fun you create a new array object B and you are just assigning the reference of new one to your local method reference variable which of-course will not have any impact on the original A object which was passed as input to the fun .

    You would need to pass it by reference if you want to reflect the changes made to A in fun to be reflected back to the original array object.

    You can update the array items without passing by reference which is explained well in Scott Chamberlain's answer

    Hope it Helps!

    链接地址: http://www.djcxy.com/p/21014.html

    上一篇: 通过ref与val,变量与数组

    下一篇: C#数组参数引用