CSharp/C# Tutorial - C# Multidimensional Arrays






Multidimensional arrays come in two varieties: rectangular and jagged.

Rectangular arrays represent an n-dimensional block of memory, and jagged arrays are arrays of arrays.

Rectangular arrays

Rectangular arrays are declared using commas to separate each dimension.

The following declares a rectangular two-dimensional array, where the dimensions are 3 by 3:


int[,] matrix = new int[3,3]; 

The GetLength method of an array returns the length for a given dimension starting at 0:


for (int i = 0; i < matrix.GetLength(0); i++) {
    for (int j = 0; j < matrix.GetLength(1); j++) {
        matrix[i,j] = i * 3 + j; 
    }
}

A rectangular array can be initialized as follows:


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




Jagged arrays

Jagged arrays are declared using successive square brackets to represent each dimension.

Here is an example of declaring a jagged two-dimensional array, where the outermost dimension is 3:


int[][] matrix = new int[3][]; 

The inner dimensions aren't specified in the declaration, each inner array can be an arbitrary length.

Each inner array is implicitly initialized to null rather than an empty array.

Each inner array must be created manually:


for (int i = 0; i < matrix.Length; i++) { 
    matrix[i] = new int[3]; // Create inner array 
    for (int j = 0; j < matrix[i].Length; j++)
        matrix[i][j] = i * 3 + j; 
    } 
}

A jagged array can be initialized as follows:


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




Array Initialization

There are two ways to shorten array initialization expressions.

The first is to omit the new operator and type qualifications:


char[] vowels = {'a','e','i','o','u'}; 
int[,] rectangularMatrix = { 
    {0,1,2}, /*from   w  w w  .  j  a  v  a 2  s.co  m*/
    {3,4,5}, 
    {6,7,8} 
}; 

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

The second approach is to use the var keyword, which tells the compiler to implicitly type a local variable:


var i = 3; // i is implicitly of type int 
var s = "asdf"; // s is implicitly of type string 
/* w  w w .jav a 2  s  .c  om*/
var rectMatrix = new int[,]{ 
    {0,1,2}, 
    {3,4,5}, 
    {6,7,8} 
}; 

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

We can omit the type qualifier after the new keyword and have the compiler infer the array type:

var letters = new[] {'a','e','i','o','u'}; // Compiler infers char[]