Skip navigation.

Blog

Passing an Empty Array in VB.Net

When needing to pass arrays around between methods, I had always initialised them as Nothing so that I knew when they were completely empty. i.e.

Dim arrayVar() As String = Nothing

This is fine, but does then mean doing an extra check before working with the array. i.e.

If arrayVar IsNot Nothing Then
    For i As Integer = 0 To arrayVar.GetUpperBound(0)
        'do other work with the array, etc
    Next
End If

The tip, is to initialise the array as size -1 instead of Nothing, i.e.

Dim arrayVar(-1) As String

This means that you then don't need the extra IsNot Nothing check, saving two lines of code every time the array is used, and allowing you to have coffee a few seconds earlier than you otherwise would!

Source: Thanks to Dayba for the original tip and allowing me to get to coffee quicker!


Reader Comments

Skip to form

There are currently no comments about this article.