Udostępnij za pośrednictwem


Multidimensional Arrays (C# Programming Guide)

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];

See Also

Concepts

C# Programming Guide

Reference

Arrays (C# Programming Guide)

Single-Dimensional Arrays (C# Programming Guide)

Jagged Arrays (C# Programming Guide)