0 day streak
csharp / intermediate
Snippet

Indexing Rectangular Multi-Dimensional Arrays

Rectangular arrays (int[,]) have a fixed size for each dimension, unlike jagged arrays. Accessing elements uses a comma-separated syntax, and GetLength is used to determine the bounds of each dimension safely.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int[,] map = new int[3, 2]
{
{ 1, 2 },
{ 3, 4 },
{ 5, 6 }
};
for (int i = 0; i < map.GetLength(0); i++)
{
for (int j = 0; j < map.GetLength(1); j++)
{
Console.Write(map[i, j] + " ");
}
}
Breakdown
1
int[,] map = new int[3, 2]
Declares a 2D rectangular array with 3 rows and 2 columns.
2
map.GetLength(0)
Retrieves the size of the first dimension (rows).