Array length

In this chapter you will learn:

  1. What is the difference between array length and array rank
  2. How to get array length with GetLength function
  3. GetLength() and two dimension array
  4. How to get the last element in an array

Rank vs array

using System;// j a v a 2  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.

Get array length with GetLength function

using System;/*java  2  s .  co m*/

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

      Console.WriteLine("GetLength(0) = {0}", arr.GetLength(0));
   }
}

The code above generates the following result.

GetLength() and two dimension array

The following code uses the GetLength() method to get number of elements in each dimension of the two dimensional array.

using System;//from  j  a  v  a  2  s. co m

class MainClass
{

  public static void Main()
  {
    string[,] names = {
      {"J", "M", "P"},
      {"S", "E", "S"},
      {"C", "A", "W"},
      {"G", "P", "J"},
    };

    int numberOfRows = names.GetLength(0);
    int numberOfColumns = names.GetLength(1);
    Console.WriteLine("Number of rows = " + numberOfRows);
    Console.WriteLine("Number of columns = " + numberOfColumns);

  }
}

The code above generates the following result.

Last element in an array

The following code uses the array length property to reference the last element in an array.

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

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

      Console.WriteLine(arr[arr.Length-1]);
   }
}

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 » Array
Array
Array loop
Array dimension
Jagged Array
Array length
Array Index
Array rank
Array foreach loop
Array ForEach Action
Array lowerbound and upperbound
Array Sort
Array search with IndexOf methods
Array binary search
Array copy
Array clone
Array reverse
Array ConvertAll action
Array Find
Array SequenceEqual