Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0054 Passing Arrays Using ref and out

An out parameter of an array type must be assigned by the callee. For example: static void TestMethod1(out int[] arr) { arr = new int[10]; // definite assignment of arr } A ref parameter of an array type must be assigned by the caller. A ref parameter of an array type may be altered as a result of the call. static void TestMethod2(ref int[] arr) { arr = new int[10]; // arr initialized to a different array } In this example we use out modifier for array parameter: class TestOut { static void FillArray(out int[] arr) { // Initialize the array: arr = new int[5] { 1, 2, 3, 4, 5 }; } static void Main() { int[] theArray; // Initialization is not required // Pass the array to the callee using out: FillArray(out theArray); // Display the array elements: foreach (int i in theArray) { System.Console.WriteLine(i); } } } The output: 1 2 3 4 5 The following code shows how to use ref modifier for array parameter. class MainClass { static void FillArray(ref int[] arr) { arr[0] = 1111; arr[4] = 5555; } static void Main() { // Initialize the array: int[] theArray = { 1, 2, 3, 4, 5 }; // Pass the array using ref: FillArray(ref theArray); // Display the updated array: foreach (int i in theArray) { System.Console.WriteLine(i); } } } The output: 1111 2 3 4 5555