csharp / intermediate
Snippet
Traversing Multi-dimensional Rectangular Arrays
Unlike jagged arrays (arrays of arrays), rectangular arrays have a fixed shape defined by commas in the square brackets. The GetLength method is used to find the bounds of specific dimensions.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MatrixProcessor {public void ProcessMatrix() {int[,] matrix = new int[2, 3] {{ 1, 2, 3 },{ 4, 5, 6 }};for (int i = 0; i < matrix.GetLength(0); i++) {for (int j = 0; j < matrix.GetLength(1); j++) {System.Console.WriteLine($"Element at [{i},{j}]: {matrix[i, j]}");}}}}
Breakdown
1
int[,] matrix = new int[2, 3]
Declares a 2D rectangular array with 2 rows and 3 columns.
2
matrix.GetLength(0)
Retrieves the size of the first dimension (rows).