How to find the length and rank of a jagged array in C#?


Firstly, set a jagged array.

int[][] arr = new int[][] {
   new int[] {
      0,
      0
   }, new int[] {
      1,
      2
   },
   new int[] {
      2,
      4
   }, new int[] {
      3,
      6
   }, new int[] {
      4,
      8
   }
};

Now, use the GetLowerBound(), GetUpperBound() and Rank property to get the lenth and rank of the array as shown in the following code −

Example

 Live Demo

using System;
public class Program {
   public static void Main() {
      int[][] arr = new int[][] {
         new int[] {
            0,
            0
         }, new int[] {
            1,
            2
         },
         new int[] {
            2,
            4
         }, new int[] {
            3,
            6
         }, new int[] {
            4,
            8
         }
      };
      // Length
      Console.WriteLine("Length:" + arr.Length);
      Console.WriteLine("Upper Bound: {0}", arr.GetUpperBound(0).ToString());
      Console.WriteLine("Lower Bound: {0}", arr.GetLowerBound(0).ToString());
      Console.WriteLine("Dimensions of Array : " + arr.Rank);
   }
}

Output

Length:5
Upper Bound: 4
Lower Bound: 0
Dimensions of Array : 1

Updated on: 22-Jun-2020

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements