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.

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

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

Community Additions

ADD
Show:
© 2015 Microsoft