VB.NET Array Length

Array type

An array stores its element count. This is returned when the Length property is accessed. The Length property returns an Integer value.
The LongLength property,
useful only for large arrays,
returns a Long value.

Example

Note

In this VB.NET program, we first allocate an array of three string literals upon the managed heap. Then, we show that the Length and LongLength properties return 3 at this point in the program.

String Array

Next:We change the array reference to point to an array of two elements. After this, the Length and LongLength properties return 2.

Program that demonstrates Length property: VB.NET

Module Module1
    Sub Main()
	' Create an array of three strings.
	Dim array() As String = {"Dot", "Net", "Perls"}
	Console.WriteLine(array.Length)
	Console.WriteLine(array.LongLength)

	' Change the array to have two strings.
	array = {"OK", "Computer"}
	Console.WriteLine(array.Length)
	Console.WriteLine(array.LongLength)

	Console.ReadLine()
    End Sub
End Module

Output

3
3
2
2
Programming tip

Length versus LongLength. The LongLength returns a larger value type storing the length. If you have a large array, such as a byte array that stores an image, LongLength might return an accurate number while Length would be truncated.

Summary

The VB.NET programming language

Arrays in the VB.NET language provide many useful properties and methods you can employ in your programs. With the Length and LongLength properties, you can instantly retrieve the current number of elements in the array.

Note:This eliminates the need for any looping or counting mechanisms, which can be hard to maintain.


VB.NET: Array