Xojo and nil arrays

Xojo can return arrays from method calls like

Function foo() as String()

Now what happens if you leave such a function without a return statement ?
Xojo will happily return a NIL array – not one that has no members but one that IS NIL

For instance, if you create the function as

Function foo() as string()
End Function

and then call it later like

dim arr() as string = foo
break

The debugger will show you that arr is NIL; not a valid array with no elements (some Xojo documentation conflates these two things but they are NOT the same)

If your code was

dim arr() as string = foo
arr.append "123"

You will get a NilObjectException (yes internally arrays are objects)

So how DO you check which it is ?

  1. use Is Nil to test if you got a NIL array
  2. use the count property if the array IS NOT NIL
dim arr() as string = foo
if arr is nil then
  // ok now how do I deal with this ?
  // how can I make it so I can add items ?
else if arr.count = 0 then
  // ok we got back an array with no items in it
  // appending items will work !
else 
  // ok we got back an array with items in it !
  // appending items will work !
end if

Notice that if we get back a NIL we cant do much since there is NO array. Trying to append will raise an exception. So what can I do to make it NOT be a nil array ?

At first you might try the Redim function to create an array like

Redim arr(-1)

in API 2 this is arr.ResizeTo like arr.ResizeTo(-1) which will also fail

The right thing to do is use the Array FUNCTION to create one with some elements then resize it to 0 like

arr = Array("")
redim arr(-1)

The resulting code then looks like

dim arr() as string = foo
if arr is nil then
  // ok got a NIL array
  // but thanks to norm we know how to fix this
  arr = Array("")
  redim arr(-1)
else if arr.count = 0 then
  // ok we got back an array with no items in it
  // appending items will work !
else 
  // ok we got back an array with items in it !
  // appending items will work !
end if

// and now here you can append items
// regardless of what the function gave you back 

Have a great day