.NET Type System, Part II - Multi-Dimension Arrays
(Page 5 of 7 )
A single-dimension array is just a simple sequence of elements, but multi-dimension arrays extend to complex sequences. This complexity involves walking in more than one dimension. For example, you can have two dimensions in your array (such as x and y) to represent screen coordinates, so you can go to point "5, 6" or "100, 400" and so on. You specify a multi-dimension array by using a comma inside the square brackets like this: int[,]. If you want a three dimension array, it looks like this: int[,,]. Sometimes multi-dimension arrays are called rectangular arrays, because all the dimensions are fixed, unlike jagged arrays, which are arrays of arrays, as we will discuss soon. The following example illustrates the use of Multi-Dimension arrays:
using System;
namespace Arrays
{
class SingleDimension
{
static void Main(string[] args)
{
int[,] points = new int[2,2];
points[0,0] = 0;
points[0,1] = 1;
points[1,0] = 6;
points[1,1] = 7;
for(int x=0; x < points.GetLength(0); x++)
{
for(int y=0; y < points.GetLength(1); y++)
{
Console.Write(points[x,y] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
The result will be the following:
0 1
6 7
Note that we have used the method GetLength() to return the length of each dimension. Dimensions are also zero-based. The Length property returns the total number of elements in all dimensions, so we didn't use it in this example.
Jagged Arrays
This is the most complex type of array you will define; fortunately, it's very uncommon to define jagged arrays, but we need to discuss it for the sake of completeness. A jagged array is simply array of arrays. In other words, it's much more like a multi-dimension array, but each dimension may vary in its element number from the other dimensions in the array. You declare a jagged array like this:
int[][] Players = new int[3][];
This simply means that we have an array called Players that contains three elements. Each element represents an array of its own that can vary in the number of elements. To initialize the elements (the arrays) of the jagged array, you can write the following code:
int[][] Players = new int[3][];
Players[0] = new int[4] {1,2,9,10};
Players[1] = new int[6] {23,12,34,35,65,14};
Players[2] = new int[11] {1,4,5,6,7,9,10,25,12,15,3};
As you can see, it's an array of arrays. In our Players jagged array we can store the players' numbers of different games, and because each game contains a different number of players, the jagged array is a perfect solution with which to store them all.
Next: C# Strings >>
More .NET Articles
More By Michael Youssef