Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

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);
    }
}

Sun Mon Tue Wed Thu Fri Sat

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 } });
    }
}

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

Community Additions

ADD
Show:
© 2015 Microsoft