C# Array Rank

In this chapter you will learn:

  1. What is the difference between array length and array rank
  2. Example:get array rank for two dimensional array

Rank vs array

What is the difference between array length and array rank?


using System;//from   w  w  w .j a v  a2 s.  c  o m

class MainClass
{
   static void Main()
   {
      int[] arr = new int[] { 15, 20, 5, 25, 10 };

      Console.WriteLine("Rank = {0}, Length = {1}", arr.Rank, arr.Length);
   }
}

The code above generates the following result.

Example

The following code shows how to get array rank for two dimensional array.


using System;/* w w w .  ja v  a2s  .  co  m*/

class MainClass {

    public static void PrintArray(int[] arr) {
        for (int i = 0; i < arr.Length; ++i)
            Console.WriteLine("OneDArray Row {0} = {1}", i, arr[i]);
    }

    public static void PrintArrayRank(int[,] arr) {
        Console.WriteLine("PrintArrayRank: {0} dimensions", arr.Rank);
    }


    public static void Main() {
        int[] x = new int[10];
        for (int i = 0; i < 10; ++i){
            x[i] = i;
        }    
        PrintArray(x);

        int[,] y = new int[10, 20];
        for (int k = 0; k < 10; ++k){
          for (int i = 0; i < 20; ++i){
             y[k, i] = i * k;
          }    
        }
        PrintArrayRank(y);
    }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Array Declaration with initialization
  2. How ro assign value to an array
  3. Set array element value by index(subscript)
  4. Index out of range exception
  5. What to do with IndexOutOfRangeException
Home »
  C# Tutorial »
    C# Language »
      C# Array
C# Arrays
C# Array Length
C# Array Rank
C# Array Index
C# Multidimensional Arrays
C# Array Initialization
C# Jagged Array
C# Array foreach loop
C# Array ForEach Action