Monday, 3 November 2008

Checking For an Empty Array

I have seen many methods for dealing with arrays in VB6 that may contain no elements over the years. From using a counter variable to handling it in an error trap. But is there a correct way of handling arrays that have not been initialised and contain no data?

Yes! If you Not an array it will return -1 if it contains no elements. Here is an example:

If (Not variableArray) = -1 Then ' Array is empty. Else ' Array has elements. End If

And there you have it. No need to use a confusing error trap looking for a subscript out of range exception, no need to declare any extra variables and remembering to set them accordingly, just one line of code.

This works because Not is performing a bitwise operation on the array's 32 bit memory pointer. If this pointer is Null then all the bits get switched on and you end up with 0xFFFFFFFF, or -1 in VB6. If you Not it a second time you will end up with the array's memory pointer, or zero if it has not been initialised.


References:

  1. How do I check if array has been initialized?

No comments: