logo search
CSharp_Prog_Guide

Передача одномерных массивов в качестве параметров

Инициализированный одномерный массив можно передать в метод. Пример.

PrintArray(theArray);

Метод, вызываемый в приведенной выше строке, может быть задан как:

void PrintArray(int[] arr)

{

// method code

}

Новый массив можно инициализировать и передать за одно действие. Пример.

PrintArray(new int[] { 1, 3, 5, 7, 9 });

Example 1

Description

In the following example, a string array is initialized and passed as a parameter to the PrintArray method, where its elements are displayed:

Code

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