logo
CSharp_Prog_Guide

Инициализация массива

Массив можно инициализировать при объявлении, как показано в следующем примере:

int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

int[, ,] array3D = new int[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } };

Можно также инициализировать массив, не указывая его размерность:

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

Если нужно создать переменную массива без инициализации, то необходимо использовать оператор new, чтобы присвоить массив переменной. Например:

int[,] array5;

array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // OK

//array5 = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error

Можно также присвоить значение элементу массива, например:

array5[2, 1] = 25;

В следующем примере кода элементы массива инициализируются значениями по умолчанию

int[,] array6 = new int[10, 10];

Jagged Arrays

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.

The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:

int[][] jaggedArray = new int[3][];

Before you can use jaggedArray, its elements must be initialized. You can initialize the elements like this:

jaggedArray[0] = new int[5];

jaggedArray[1] = new int[4];

jaggedArray[2] = new int[2];

Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers.

It is also possible to use initializers to fill the array elements with values, in which case you do not need the array size. For example:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };

jaggedArray[1] = new int[] { 0, 2, 4, 6 };

jaggedArray[2] = new int[] { 11, 22 };

You can also initialize the array upon declaration like this:

int[][] jaggedArray2 = new int[][]

{

new int[] {1,3,5,7,9},

new int[] {0,2,4,6},

new int[] {11,22}

};

You can use the following shorthand form. Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements:

int[][] jaggedArray3 =

{

new int[] {1,3,5,7,9},

new int[] {0,2,4,6},

new int[] {11,22}

};

A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.