C Sharp

Multidimensional Arrays

In addition to single-dimensional arrays, C# supports the declaration of multidimensional arrays where each dimension of the array is separated by a comma. Here I'm declaring a three-dimensional array of doubles: -

double[,,] numbers;

To quickly determine the number of dimensions in a declared C# array, count the number of commas and add one to that total.

In the following example, I have a two-dimensional array of sales figures that represent this year's year-to-date figures and last year's totals for the same time frame. Take special note of the syntax used to instantiate the array (in the MultiDimArrayApp constructor).

using System;
class MultiDimArrayApp
    protected int currentMonth;
    protected double[,] sales;
        sales = new double[2, currentMonth];
        for (int i = 0; i < sales.GetLength(0); i++)
            for (int j=0; j < 10; j++)
                sales[i,j] = (i * 100) + j;
    protected void PrintSales()
        for (int i = 0; i < sales.GetLength(0); i++)
            for (int j=0; j < sales.GetLength(1); j++)
                Console.WriteLine("[{0}][{1}]={2}", i, j, sales[i,j]);
    public static void Main()
        MultiDimArrayApp app = new MultiDimArrayApp();

Running the MultiDimArrayApp example results in this output: -


Remember that in the single-dimensional array example I said the Length property will return the total number of items in the array, so in this example that return value would be 20. In the MultiDimArray.PrintSales method I used the Array.GetLength method to determine the length or upper bound of each dimension of the array. I was then able to use each specific value in the PrintSales method.