WELCOME

This blog is where I post about my consulting work with Microsoft Technologies, and other random tidbits that don't fit in my Photo Blog or my Iraq Blog.

Wednesday, June 18, 2008

VB6 Migration: Non-zero based arrays

VB6 allows you to define arrays that are non-zero based, for example:

Dim RecentPolicies(1 to 4) as String

In .NET all arrays are zero based and the migration wizard generates the following code:

'UPGRADE_WARNING: Lower bound of array RecentPolicies was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'

Public RecentPolicies(4) As String

This is frankly evil, the migration wizard does NOT fix any of the related code, and so have go fix are you code. For example:

RecentPolicies(intI) would need to be changed to: RecentPolicies(intI - 1)

But I was thrilled to discover yesterday that Francesco Balena has come up with a really slick solution to this problem, which is essentially a new type that supports non-zero based arrays! So instead of the ickyness described above you can simply change your VB.NET 2.0 code to:

Dim RecentPolicies As New VBArray(Of String )(1, 4)

This is incredible time savings! To get the code read Francesco's original blog post here: http://www.dotnet2themax.com/blogs/fbalena/PermaLink,guid,08e740fc-f486-4b5b-8796-6aad43e08815.aspx

Caveat: This is a Visual Basic 2005 specific solution (due to the use of generics).

Being inherintly sceptical of new things, I wrote the following set of NUnit tests to prove that his code works:

Imports NUnit.Framework

_

Public Class VBArrayTests

_

Public Sub TestLowerBound()

Dim _array As New VBArray(Of Short)(1, 3)

Assert.AreEqual(1, LBound(_array), "Lower bound should equal 1")

End Sub

_

Public Sub TestUpperBound()

Dim _array As New VBArray(Of Short)(1, 3)

Assert.AreEqual(3, UBound(_array), "Upper bound should equal 3")

End Sub

_

Public Sub TestZeroIndex()

Dim _array As New VBArray(Of Short)(1, 3)

Try

_array(0) = 55

Catch ex As System.IndexOutOfRangeException

Assert.IsTrue(True, "System.IndexOutOfRangeException exception was thrown on zero index")

End Try

End Sub

_

Public Sub TestMaxIndex()

Dim _array As New VBArray(Of Short)(1, 3)

Try

_array(4) = 55

Catch ex As System.IndexOutOfRangeException

Assert.IsTrue(True, "System.IndexOutOfRangeException exception was thrown on index of 4")

End Try

End Sub

End Class

No comments: