Export (0) Print
Expand All
33 out of 43 rated this helpful - Rate this topic

Passing Arrays Using ref and out

Like all out parameters, an out parameter of an array type must be assigned before it is used; that is, it must be assigned by the callee. For example:

public static void MyMethod(out int[] arr) 
{
   arr = new int[10];   // definite assignment of arr
}

Like all ref parameters, a ref parameter of an array type must be definitely assigned by the caller. Therefore, there is no need to be definitely assigned by the callee. A ref parameter of an array type may be altered as a result of the call. For example, the array can be assigned the null value or can be initialized to a different array. For example:

public static void MyMethod(ref int[] arr) 
{
   arr = new int[10];   // arr initialized to a different array
}

The following two examples demonstrate the difference between out and ref when used in passing arrays to methods.

Example 1

In this example, the array myArray is declared in the caller (the Main method), and initialized in the FillArray method. Then, the array elements are returned to the caller and displayed.

// cs_array_ref_and_out.cs
using System; 
class TestOut 
{
   static public void FillArray(out int[] myArray) 
   {
      // Initialize the array:
      myArray = new int[5] {1, 2, 3, 4, 5};
   }

   static public void Main() 
   {
      int[] myArray; // Initialization is not required

      // Pass the array to the callee using out:
      FillArray(out myArray);

      // Display the array elements:
      Console.WriteLine("Array elements are:");
      for (int i=0; i < myArray.Length; i++)
         Console.WriteLine(myArray[i]);
   }
}

Output

Array elements are:
1
2
3
4
5

Example 2

In this example, the array myArray is initialized in the caller (the Main method), and passed to the FillArray method by using the ref parameter. Some of the array elements are updated in the FillArray method. Then, the array elements are returned to the caller and displayed.

// cs_array_ref_and_out2.cs
using System; 
class TestRef 
{
   public static void FillArray(ref int[] arr) 
   {
      // Create the array on demand:
      if (arr == null)
         arr = new int[10];
      // Otherwise fill the array:
      arr[0] = 123;
      arr[4] = 1024;
   }

   static public void Main () 
   {
      // Initialize the array:
      int[] myArray = {1,2,3,4,5};  

      // Pass the array using ref:
      FillArray(ref myArray);

      // Display the updated array:
      Console.WriteLine("Array elements are:");
      for (int i = 0; i < myArray.Length; i++) 
         Console.WriteLine(myArray[i]);
   }
}

Output

Array elements are:
123
2
3
4
1024

See Also

Arrays

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.