C# Multidimensional Arrays
Introduction to Multidimensional Arrays
In C#, a multidimensional array is an array with more than one dimension, such as a 2D array (matrix) or 3D array.
These arrays are especially useful for representing structured data like grids, tables, game boards, or mathematical matrices.
Declaring a 2D Array
A 2D array is declared by specifying two dimensions in square brackets, e.g., int[,] matrix.
You can initialize the array with values directly in a block or allocate it with sizes and assign values later.
Example
using System;
namespace TwoDArrayExample
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
Output
1 2 3 4 5 6 7 8 9
3D Arrays
C# also supports three-dimensional arrays, which can be thought of as arrays of 2D layers.
They are declared using three dimensions in square brackets, e.g., int[,,] cube.
Example
using System;
namespace ThreeDArrayExample
{
class Program
{
static void Main(string[] args)
{
int[,,] cube = new int[2, 2, 2]
{
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
};
for (int i = 0; i < cube.GetLength(0); i++)
{
for (int j = 0; j < cube.GetLength(1); j++)
{
for (int k = 0; k < cube.GetLength(2); k++)
{
Console.Write(cube[i, j, k] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
}
}
Output
1 2 3 4 5 6 7 8