Create zero-elements arrays

Create zero-elements arrays

The .NET framework lets you create two types of “empty” arrays: unitialized arrays and arrays that are initialized with zero elements. Uninitialized arrays are actually array variables that are set to Nothing, whereas zero-element arrays are non-Nothing variables that point to arrays with zero elements. Here is the (undocumented) method for creating zero-element arrays:

Dim arr(-1) As Integer   ' or whatever type you need

If you have a routine that returns an array, you can decide whether you want to return Nothing or a zero-element array when an empty array should be returned. In general, returning a zero-element array makes for a more linear code in the caller. Consider this routine, that returns all the items in a string array that contain a given substring:

Function Matches(ByVal arr() As String, ByVal Search As String) As String()    Dim al As New ArrayList()    Dim s As String    For Each s In arr        If s.IndexOf(Search) >= 0 Then al.Add    Next    ' return Nothing if no matches    If al.Count Then Return Nothing    ' else move the elements into a string array    Dim res(al.Count - 1) As String    Dim i As Integer    For i = 0 To al.Count - 1        res(i) = al(i)    Next    ' return the array    Return resEnd Function

The caller of the above routine must discern the Nothing case from regular case:

Dim res() As String = Matches( arr, "Find this")If res Is Nothing Then    Console.WriteLine("Found 0 matches")Else    Console.WriteLine("Found {0} matches", res.Length)End If

Now, consider what happens if you delete these two lines in the Matches routine:

    ' return Nothing if no matches    If al.Count Then Return Nothing

Not only is the Matches routine simpler, also the caller requires less code, because it doesn’t have to check for Nothing first:

Dim res() As String = Matches( arr, "Find this")Console.WriteLine("Found {0} matches", res.Length)


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist