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.
Example. 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.
Part 1 We use the Length property and assign a local variable integer (length1) to this value.
Part 3 We initialize an empty array, and then access Length on it. This returns the value 0, as expected.
Part 4 Arrays have 1 or more dimensions. With 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
2D arrays. 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.
Info The array in this program has 3 rows and 2 columns. For rank 0, we get 3 (for rows), and for rank 1, we get 2 (columns).
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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.