Appending to upcasted array crashes SortWith

I’ve pinned down a crash where if an array has been upcasted and you append or insert to that then SortWith will crash.

dim dateArr() As Date             //starting array

dim objArr() As Object = dateArr  //upcast

objArr.Append new Date            //append to upcasted
objArr.Append new Date

dim indices() As integer = Array(2, 1)

break
indices.SortWith(objArr)          //crash

I ran into this while making a method that collects items of a Control Set into an array sorted by Index. To be generic the methods parameter is ‘arr() As Control’ and I’d pass in an array of the specific type.

[code]dim tfa() As TextField
collectSet(“TextField1”, tfa)

Sub collectSet(name As String, arr() As Control)
…[/code]

workarounds

re-upcast just before SortWith

objArr = dateArr indices.SortWith(objArr)

if you’re not able to re-upcast (my situation) then use another array and copy that over after SortWith

[code]dim otherArr() As Object

indices.SortWith(otherArr)

for i As integer = 0 to otherArr.Ubound
objArr.Append otherArr(i)
next[/code]

Is it really a crash or are you getting an exception of some kind?

On OS X it crashes with:

[code]Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000000

[…]

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 libsystem_platform.dylib 0x913b9332 _platform_memmove$VARIANT$sse42 + 34
1 com.xojo.XojoFramework 0x002af213 0x135000 + 1548819
2 com.xojo.XojoFramework 0x002c0dce 0x135000 + 1621454
[…][/code]