Variant Array shenanigans?

From Object Array shenanigans - General - Xojo Programming Forum

I have a shared method into which I pass arrays of controls (mix of rectControls and containerControls) to effect alignment. I was previously using variant arrays and sometimes had problems when there was only one type of item in the array - the compiler would then seem to auto format as a array of the item’s type, rather than a variant array.

Can anyone (Norman?) confirm that? Seems like a serious bug to me …

That is normal for array function.
But you can put first value into variant first to make sure you get that type.

Seriously? Seems idiotic to me. Just because I first added 100 classA objects doesn’t mean it should now be an array of classA objects and throw a TypeMismatch exception when I try to add a classB object.

:thinking:

What do you mean with “normal for array function”? “Normal” for arrays in all languages, or “normal” for Xojo arrays?

That is not what is happening here. The assignment of the array created to the receiving variable is failing due to a type mismatch.

If all arguments in the Array() function are of the same type, the compiler infers that as the return type.

But if the arguments to the Array() function are of different types the returned array is typed as Variant(), which of course you cannot assign to a variable typed as Object().

For example this works:

Dim arr() As Integer = Array(1, 2, 3)
Dim arr() As Object = Array(new Canvas(), new Canvas())

This does not work:
Dim arr() As Object = Array(new Canvas(), new RectControl())

But this will work:
Dim arr() As Variant = Array(new Canvas(), new RectControl())
Dim arr() As Variant = Array(1, 2, new RectControl())

I do not consider this to be a bug. In theory the compiler could try to find a common superclass to all the arguments and only return an array of Variants if there is no common superclass.

Then this would work (because both arguments are either of type RectControl or inherit from RectControl):

Dim arr() As Object = Array(new Canvas(), new RectControl())
Dim arr() As RectControl = Array(new Canvas(), new RectControl())

But I assume this would be difficult to implement.

Well, the function is very simply. The array type is defined by first item in list.
That is why I always may have to add a “.0” for the first number to get double array.