C# Array Length

In this chapter you will learn:

  1. What is C# Array Length
  2. How to access C# Array Length
  3. How to use array length property
  4. How to get array length with GetLength function
  5. GetLength() and two dimension array

Description

The Length property of an array returns the number of elements in the array.

Once an array has been created, its length cannot be changed.

Syntax

Here is the syntax we can use to access array length property.

arrayVariable.Length;

Example

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


using System;/* ww  w.j  a v  a  2  s .co  m*/

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

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

The code above generates the following result.

Example 2


using System;/*from www .  ja va 2  s . com*/

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.

Example 3

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


using System;/*w  w w .  java 2  s  . c o  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.

Next chapter...

What you will learn in the next chapter:

  1. What is the difference between array length and array rank
  2. Example:get array rank for two dimensional array
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