VB.Net Array Testing is Nothing and Array Length

When working with .net languages, you may have come across some subtle difference between the languages in terms of how different situations are handled. One of these situations is the If statement. If you want to check an array to make sure it is not nothing and also contains elements, you may be tempted to try something like this:

	If Not MyArray is nothing And MyArray.Length > 0 then
	' Do Something
	End If

Or

	If MyArray is nothing Or MyArray.Length = 0 then
	' Do Something
	End If

You may expect that the ‘And’ operator and ‘Or’ operator will exit early, but this is not the case. But to handle this specific scenario, there exists the ‘AndAlso’ and ‘OrElse’ operators. To prove that the problem exists and is resolvable – you may try the following code in a basic Console Application Template:

	Dim b As Array = Nothing
        Try
            If Not b Is Nothing And b.Length = 0 Then

                Console.WriteLine("Array is nothing")
            Else
                Console.WriteLine("Array is Something")
            End If
        Catch ex As NullReferenceException
            Console.WriteLine(ex.Message)
        End Try

        Try
            If b Is Nothing Or b.Length = 0 Then

                Console.WriteLine("Array is nothing")
            Else
                Console.WriteLine("Array is Something")
            End If
        Catch ex As NullReferenceException
            Console.WriteLine(ex.Message)
        End Try

        Try
            If Not b Is Nothing AndAlso b.Length > 0 Then
                Console.WriteLine("Array is Something")
            Else
                Console.WriteLine("Array is nothing or 0")
            End If
        Catch ex As NullReferenceException
            Console.WriteLine(ex.Message)
        End Try

        Try
            If b Is Nothing OrElse b.Length > 0 Then

                Console.WriteLine("Array is nothing or 0")
            Else
                Console.WriteLine("Array is Something")
            End If
        Catch ex As NullReferenceException
            Console.WriteLine(ex.Message)
        End Try

The output should look something like this:

Object reference not set to an instance of an object.
Object reference not set to an instance of an object.
Array is nothing or 0
Array is nothing or 0
Press any key to continue . . .

ttessier

About ttessier

Professional Developer and Operator of SwhistleSoft
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *