Comparing Array References to Nil

· Feb 23, 02:57 PM

The inability to compare an array reference to Nil is a longstanding REALbasic annoyance. It is now possible to do so in REALbasic 2008r1, albeit obliquely.

In REALbasic 2008r1, the Variant class now supports storage of array references. So to compare an array reference to Nil, assign the reference to a Variant and test it.

dim s() as String = SomeFunctionThatReturnsAnArray
 dim v as Variant = s
 if v = nil then
   //s is nil
 else
   //s is not nil
 end if

You can eliminate the code duplication to follow with a global method IsNil.

Function IsNil(v as Variant) as Boolean
   return v.IsNull
 End Function

It appears that Variants are always initialized, so this code will not result in a NilObjectException when v is nil.

Now you can write code like the following.

dim s() as String = SomeFunctionThatReturnsAnArray
 if IsNil(s) then
   //s is nil
 else
   //s is not nil
 end if

One needs to be able to compare array references to nil because array references are mutable.

dim s() as String = SomeFunctionThatReturnsAnArray

Firsthand experience suggests that it’s possible that the implementor of SomeFunctionThatReturnsAnArray can and will forget to return an array reference, resulting in s being set to nil. Subsequent operations involving s may result in a NilObjectException.

if UBound(s) > -1 then

or an application crash

dim foo as String = s(0).

There is a feedback request for comparison of array references to nil. Until that request is implemented, the IsNil function above might save you some crash-hunting.

---

Comment

  1. Nice function and thanks in particular for pointing out that people forgetting to return an array can create nil array references. I had forgotten that was possible in RB and so was not as bothered about the inability to compare arrays to nil.

    Andy Dent · Mar 6, 12:15 PM · #

  2. Thanks. And now I’ve fixed the code formatting in the article.

    charles · Mar 6, 12:29 PM · #

Commenting is closed for this article.