Length
, arrayHow many elements are in an array? In VB.NET programs, we must account for empty arrays, 1D arrays, and sometimes 2D arrays.
With properties like Length
and LongLength
, we get values that indicate array element count. These values are stored by the arrays, so they are fast to access.
We use the Main
Subroutine to run some array-length testing code. We first need to create some arrays—we initialize a 3-element String
array.
Length
property and assign a local variable integer (length1) to this value.LongLength
property is available, and this helps when the array contains more elements than can be represented as an Integer.Length
on it. This returns the value 0, as expected.GetLength
, the argument indicates the rank (dimension) we want to measure.Module Module1 Sub Main() ' Part 1: access Length property. Dim array1() as String = { "cat", "apple", "frog" } Dim length1 as Integer = array1.Length Console.WriteLine("LENGTH: {0}", length1) ' Part 2: access LongLength. Dim longLength1 as Long = array1.LongLength Console.WriteLine("LONGLENGTH: {0}", longLength1) ' Part 3: get Length of zero-length array. Dim array2() as Integer = { } Dim length2 = array2.Length Console.WriteLine("LENGTH: {0}", length2) ' Part 4: get length for rank 0 of first array. Dim length3 = array1.GetLength(0) Console.WriteLine("LENGTH: {0}", length3) End Sub End ModuleLENGTH: 3 LONGLENGTH: 3 LENGTH: 0 LENGTH: 3
Consider now 2D arrays—these have a total length of elements, but each dimension (or rank) also has a length. The GetLength()
function returns the length for a certain rank.
Module Module1 Sub Main() ' Use GetLength on 2D array. Dim two(,) As Integer = New Integer(,) { { 10, 20 }, { 30, 40 }, { 50, 60 } } Console.WriteLine("GETLENGTH: {0}", two.GetLength(0)) Console.WriteLine("GETLENGTH: {0}", two.GetLength(1)) ' Use Length on 2D array. Console.WriteLine("LENGTH: {0}", two.Length) End Sub End ModuleGETLENGTH: 3 GETLENGTH: 2 LENGTH: 6
In VB.NET, all arrays know their lengths, and this value can be accessed instantly with Length
. For 2D arrays, the situation is more complex, but GetLength
can be used.