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;
    MultiDimArrayApp()
    {
        currentMonth=10;
        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();
        app.PrintSales();
    }
}

Running the MultiDimArrayApp example results in this output: -

[0][0]=0
[0][1]=1
[0][2]=2
[0][3]=3
[0][4]=4
[0][5]=5
[0][6]=6
[0][7]=7
[0][8]=8
[0][9]=9
[1][0]=100
[1][1]=101
[1][2]=102
[1][3]=103
[1][4]=104
[1][5]=105
[1][6]=106
[1][7]=107
[1][8]=108
[1][9]=109

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.

by BrainBellupdated
Advertisement: