C Sharp

Querying for Rank

Now that we've seen how easy it is to dynamically iterate through a single- dimensional or multidimensional array, you might be wondering how to determine the number of dimensions in an array programmatically. The number of dimensions in an array is called an array's rank, and rank is retrieved using the Array.Rank property. Here's an example of doing just that on several arrays: -

using System;
class RankArrayApp
{
    int[] singleD;
    int[,] doubleD;
    int[,,] tripleD;
    protected RankArrayApp()
    {
        singleD = new int[6];
        doubleD = new int[6,7];
        tripleD = new int[6,7,8];
    }
    protected void PrintRanks()
    {
        Console.WriteLine("singleD Rank = {0}", singleD.Rank);
        Console.WriteLine("doubleD Rank = {0}", doubleD.Rank);
        Console.WriteLine("tripleD Rank = {0}", tripleD.Rank);
    }
    public static void Main()
    {
        RankArrayApp app = new RankArrayApp();
        app.PrintRanks();
    }
}

As expected, the RankArrayApp application outputs the following: -

singleD Rank = 1
doubleD Rank = 2
tripleD Rank = 3

by BrainBellupdated
Advertisement: