logo search
CSharp_Prog_Guide

Массивы типов значений и ссылочных типов.

Рассмотрим следующие объявления массива:

SomeType[] array4 = new SomeType[10];

Результат этого оператора зависит от того, является ли SomeType типом значения или ссылочным типом. Если это тип значения, оператор создает массив из 10 экземпляров типа SomeType. Если SomeType — ссылочный тип, оператор создает массив из 10 элементов, каждый из которых инициализируется нулевой ссылкой null.

Multidimensional Arrays

Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns:

int[,] array = new int[4, 2];

Also, the following declaration creates an array of three dimensions, 4, 2, and 3:

int[, ,] array1 = new int[4, 2, 3];

Array Initialization

You can initialize the array upon declaration as shown in the following example:

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

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

You can also initialize the array without specifying the rank:

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

If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:

int[,] array5;

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

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

You can also assign a value to an array element, for example:

array5[2, 1] = 25;

The following code example initializes the array variables to default (except for jagged arrays):

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