C# Multidimensional Arrays

So far every array has been a single row of values, called a one-dimensional array. A multidimensional array stores values in a grid of rows and columns, which is perfect for things like a game board, a seating chart, or a table of numbers. The most common type is the two-dimensional array.

Creating a 2D Array

To declare a two-dimensional array you put a comma inside the square brackets. You can think of it as a table where the first number is the row and the second number is the column. Each inner set of curly braces represents one row.

Declaring a 2D array

// A grid with 2 rows and 3 columns
int[,] numbers = {
    {1, 2, 3},
    {4, 5, 6}
};

Console.WriteLine(numbers[0, 0]); // 1 (row 0, column 0)
Console.WriteLine(numbers[1, 2]); // 6 (row 1, column 2)

Changing Values

You access and update an element by giving both its row and column index, separated by a comma. Just like with one-dimensional arrays, indexes start at 0.

Updating an element

int[,] numbers = {
    {1, 2, 3},
    {4, 5, 6}
};

numbers[0, 0] = 10;
Console.WriteLine(numbers[0, 0]); // 10

Looping Through a 2D Array

To visit every cell you usually use two nested for loops: an outer loop for the rows and an inner loop for the columns. The GetLength() method tells you the size of each dimension, where GetLength(0) is the number of rows and GetLength(1) is the number of columns.

Nested loops over a grid

int[,] numbers = {
    {1, 2, 3},
    {4, 5, 6}
};

for (int i = 0; i < numbers.GetLength(0); i++)
{
    for (int j = 0; j < numbers.GetLength(1); j++)
    {
        Console.Write(numbers[i, j] + " ");
    }
    Console.WriteLine();
}
// 1 2 3
// 4 5 6
  • int[,] is a two-dimensional array (rows and columns).
  • int[,,] is a three-dimensional array, adding depth as well.
  • The more dimensions you add, the harder the code is to read, so keep it to what you truly need.
Note: A foreach loop also works on a 2D array and will visit every element, but it gives you the values in a flat order without telling you the row and column, so nested for loops are usually clearer.