Multidimensional Arrays


Ordinary arrays (also known as 1-dimensional arrays) are indexed by a single integer. A multidimensional array is indexed by two or more integers.

Figure 5-3 shows the mathematical notation for a 2-dimensional array that has three rows and three columns. The first row has the values 1, 2 and 3, whereas the third row has the values 7, 8 and 9.

image from book
Figure 5-3

Declaring this 2-dimensional array with C# is done by putting a semicolon inside the brackets. The array is initialized by specifying the size of every dimension (also known as rank). Then the array elements can be accessed by using two integers with the indexer:

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

Tip 

You cannot change the rank after declaring an array.

You can also initialize the 2-dimensional array by using an array indexer if you know the value for the elements in advance. For the initialization of the array, one outer curly bracket is used, and every row is initialized by using curly brackets inside the outer curly brackets.

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

Tip 

When using an array initializer, you must you must initialize every element of the array. It is not possible to leave the initialization for some values.

By using two semicolons inside the brackets, you can declare a 3-dimensional array:

  int[,,] threedim = {                      { { 1, 2 }, { 3, 4 } },                      { { 5, 6 }, { 7, 8 } },                      { { 9, 10 }, { 11, 12 } }                    }; Console.WriteLine(threedim[0, 1, 1]); 




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net