Use of LowerBound and UpperBound with Array in VB.NET
Array has an upper and lower bound and array class provides us functions to get the minimum and maximum index value of an array.
Each dimension in an array has an upper and lower bound, which determine the range of values that can be used as subscripts for that dimension. Array class provides us functions to get the upper and lower bound or minimum and maximum index value of an array.
When the bounds are specified in array declarators:
- The lower bound is a specification expression.
- The upper bound is a specification expression or asterisk (*).
To get the lower bound of an array we use GetLowerBound() funtion. It takes dimention as a parameter and returns the lower bound of array.
To get the upper bound of an array we use GetUpperBound() funtion. It takes dimention as a parameter and returns the upper bound of array.
Example
Public Class Test
Public Shared Sub Main()
Dim Names(5) As String
Dim Counter As Integer
Console.WriteLine("LowerBound: " & Names.GetLowerBound(0))
Console.WriteLine("UpperBound: " & Names.GetUpperBound(0))
Console.WriteLine("Total Length: " & Names.Length)
For Counter = 0 To Names.GetUpperBound(0)
Names(Counter) = "Position of the Value = " & Counter
Next Counter
For Counter = 0 To Names.GetUpperBound(0)
Console.WriteLine("Position of the Value = " & Counter)
Next Counter
Console.ReadLine()
End Sub
End Class
The Data array now has 30 elements, starting from Data(0), which is how you refer to the first element, up to Data(29). 0 is the lower bound of this array, and 19 is the upper bound, the lower bound of every array index is 0.
You can find the upper bound of an array with the GetUpperBound function, which makes it easy to loop over all the elements in an array using a For loop like this:
For Counter = 0 To Names.GetUpperBound(0)...
Output