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.
Passing single-dimensional arrays as parameters
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 });
Example 1
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);
}
}
Output 1
Sun Mon Tue Wed Thu Fri Sat
Passing multidimensional arrays as parameters
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 } });
Example 2
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 } });
}
}
Output 2
Element(0,0)=1
Element(0,1)=2
Element(1,0)=3
Element(1,1)=4
Element(2,0)=5
Element(2,1)=6
Element(3,0)=7
Element(3,1)=8
See Also
Reference
Single-Dimensional Arrays (C# Programming Guide)
Multidimensional Arrays (C# Programming Guide)
Jagged Arrays (C# Programming Guide)