C# makes the distinction between jagged and multi-dimensional arrays. Elements of a multi-dimensional array are stored in a contiguous block in memory while elements of a jagged array are not. Java arrays are actually jagged arrays, while C# supports both and allows you to choose which one you want based on the syntax of your code. Note that multi-dimensional arrays are better (in most cases) than jagged arrays.
Using jagged arrays in C# is not as simple as in Java. It’s almost like the way we would implement it in C++.
int[][] jaggedArray = new int[2][];
jaggedArray[0] = new int[4];
jaggedArray[1] = new int[3];
However, multi-dimensional arrays in C# are very simply to use. You can create a 3 dimensional array as follows:
int[,,] array3D = new int[x, y, z];
then access its elements at array3D[i][j][k]
.
Sample Code:
static void Main(string[] args)
{
// Array 3 Dimensions int x = 4, y = 5, z = 6;
// Array Iterators int i, j, k;
// Allocate 3D Array int[,,] array3D = new int[x, y, z];
// Access array elements for (i = 0; i < x; i++)
{
Console.WriteLine(i);
for (j = 0; j < y; j++)
{
Console.WriteLine();
for (k = 0; k < z; k++)
{
array3D[i, j, k] = (i * y * z) + (j * z) + k;
Console.Write("\t{0}", array3D[i, j, k]);
}
}
Console.WriteLine('\n');
}
}