C# Array Length

Description

Array Length gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.

Syntax

Array.Length has the following syntax.


public int Length { get; }

Example

The following example uses the Length property to get the total number of elements in an array. It also uses the GetUpperBound method to determine the number of elements in each dimension of a multidimensional array.


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

public class MainClass
{
   public static void Main(){
      String[] array1d = { "zero", "one", "two", "three" };
      ShowArrayInfo(array1d);

      String[,] array2d= { { "zero", "0" }, { "one", "1" }, 
                           { "two", "2" }, { "three", "3"},
                           { "four", "4" }, { "five", "5" } };
      ShowArrayInfo(array2d);                             
   }

   private static void ShowArrayInfo(Array arr)
   {
      Console.WriteLine("Length of Array:      {0,3}", arr.Length);
      Console.WriteLine("Number of Dimensions: {0,3}", arr.Rank);

      if (arr.Rank > 1) {
         for (int dimension = 1; dimension <= arr.Rank; dimension++)
            Console.WriteLine("   Dimension {0}: {1,3}", dimension, 
                              arr.GetUpperBound(dimension - 1) + 1);
      }
      Console.WriteLine();
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version