Array parameter passing in C #: why is it implicitly by reference?

Suppose the following code without the ref keyword, which obviously does not replace the passed variable, because it is passed as a value.

 class ProgramInt { public static void Test(int i) // Pass by Value { i = 2; // Working on copy. } static void Main(string[] args) { int i = 1; ProgramInt.Test(i); Console.WriteLine(i); Console.Read(); // Output: 1 } } 

Now, to make this function work as expected, you could add the ref keyword as usual:

 class ProgramIntRef { public static void Test(ref int i) // Pass by Reference { i = 2; // Working on reference. } static void Main(string[] args) { int i = 1; ProgramInt.Test(ref i); Console.WriteLine(i); Console.Read(); // Output: 2 } } 

Now I'm puzzled by why array members are passed implicitly by reference when passing to functions. Are array value types?

 class ProgramIntArray { public static void Test(int[] ia) // Pass by Value { ia[0] = 2; // Working as reference? } static void Main(string[] args) { int[] test = new int[] { 1 }; ProgramIntArray.Test(test); Console.WriteLine(test[0]); Console.Read(); // Output: 2 } } 
+7
arrays parameter-passing pass-by-reference pass-by-value c #
source share
6 answers

No, arrays are classes, which means they are reference types.

+16
source share

Arrays are not passed by reference. Array references are passed by value. If it is necessary to change the WHAT array, the variable of the array of transferred values ​​indicates (for example, to change the size of the array), the variable must be passed by reference.

+2
source share

A good way to remember this:

  • "ref" makes a variable alias
  • an array is a collection of variables; each element is a variable.

When you pass an array normally, you pass a set of variables. Variables in the collection are not changed.

When you pass an array with "ref", you specify the new name of the variable containing the array.

When you pass an element of an array, you usually pass a value in a variable.

When you pass an array element - a variable - using "ref", you specify a new name for this variable.

Make sense?

+2
source share

Can you imagine how to pass an array of 2 million elements by value? Now imagine that the element type is decimal . You will need to copy about 240MB of 30.5175781MB of data.

+1
source share

As the MSDN link indicates, arrays are objects (System.Array is the abstract base type of all arrays) and objects are passed by reference.

0
source share

In addition to the basic data types, you cannot transfer anything else, except by value, Array is a set of basic data types that also allows you to transfer multiple copies of the collection by value to the collection, which would be bad for performance.

0
source share

All Articles