Posted by: Phil Weber, VB MVPThis post applies to Visual Basic .NET 2002/2003/2005
OK, now that Paul Vick has explained why VB.NET doesn't support arrays with non-zero lower bounds, let's see how we can do them anyway. ;-)
Say you want to store a collection of annual values in an array of integers. It's reasonable that the array index would correspond to the year in question; that is, TotalSales(1981) would contain the sales total for the year 1981.
In pre-.NET versions of VB, we could simply do this:
Dim TotalSales(1981 To 2000) As Integer
Dim TotalSales As New VBArray(1981, 2000) TotalSales(1981) = 345 TotalSales(2000) = 995 Console.WriteLine(TotalSales(1981)) Console.WriteLine(TotalSales(2000))
This class (based on this post by Eric Gunnerson) is what makes it all possible:
Public Class VBArray Private _lbound As Integer Private _int() As Integer Public Sub New(ByVal LBound As Integer, ByVal UBound As Integer) Me.ReDim(LBound, UBound) End Sub Public Sub [ReDim](ByVal LBound As Integer, ByVal UBound As Integer) _lbound = LBound ReDim _int(UBound - LBound + 1) End Sub Default Public Property Item(ByVal Index As Integer) As Integer Get Return _int(Index - _lbound) End Get Set(ByVal Value As Integer) _int(Index - _lbound) = Value End Set End Property Public Function ToArray() As Integer() Return _int End Function End Class
Note that this class is hard-coded to handle Integers; in VB.NET 2002/2003, you must create a separate class for each array type you wish to simulate. Generics in Visual Basic .NET 2005 will make this sort of thing much cleaner.