Passing Arrays as Parameters (C# Programming Guide)
Arrays may be passed to methods as parameters. As arrays are reference types, the method can change the value of the elements.
You can pass an initialized single-dimensional array to a method. For example:
PrintArray(theArray);
The method called in the line above could be defined as:
void PrintArray(int[] arr) { // method code }
You can also initialize and pass a new array in one step. For example:
PrintArray(new int[] { 1, 3, 5, 7, 9 });
In the following example, a string array is initialized and passed as a parameter to the PrintArray method, where its elements are displayed:
class ArrayClass { static void PrintArray(string[] arr) { for (int i = 0; i < arr.Length; i++) { System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : ""); } System.Console.WriteLine(); } static void Main() { // Declare and initialize an array: string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // Pass the array as a parameter: PrintArray(weekDays); } }
You can pass an initialized multidimensional array to a method. For example, if theArray is a two dimensional array:
PrintArray(theArray);
The method called in the line above could be defined as:
void PrintArray(int[,] arr) { // method code }
You can also initialize and pass a new array in one step. For example:
PrintArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });
In this example, a two-dimensional array is initialized and passed to the PrintArray method, where its elements are displayed.
class ArrayClass2D { static void PrintArray(int[,] arr) { // Display the array elements: for (int i = 0; i < 4; i++) { for (int j = 0; j < 2; j++) { System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]); } } } static void Main() { // Pass the array as a parameter: PrintArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }); } }