IllegalCast

My app opens a “Maintenance window” from a parent window. I now need the parent window to open any number of maintenance windows, each of which handles a different kind of data. To do this, I have an array of WeakRefs to store the various maintenance windows in. That way when I close one of the maintenance windows, its array entry can go nil and I remove it from the array. My goal is that when the user needs a new maintenance window, I don’t want them to be able to open more than one for each kind of data.

However, in the code that searches for a duplicate entry, I’m getting an IllegalCast exception and for the life of me I can’t see why.

‘WhichWnd is the parent window
‘.MyMaintWnds() is the array of WeakRefs which hold references to Maintenance windows
‘.MyCid is a category ID number that identifies the categoryID number of the data in the Maintenance window

‘The goal: If a maintenance window with this category already exists, then show it, here is the relevant code:

For i As Integer = 0 To UBound(WhichWnd.MyMaintWnds)
  
  If WhichWnd.MyMaintWnds(i)<>Nil Then 'The WeakRef in MyMaintWnds() isn't Nil
   
      'This line is OK:
    If MaintenanceWnd(WhichWnd.MyMaintWnds(i))<>Nil Then
      
      'An IllegalCast exception happens in this next line, even though .MyMaintWnds(i) is a WeakRef to an existing MaintenanceWnd:
      
      If MaintenanceWnd(WhichWnd.MyMaintWnds(i)).MyCid=WhichCat Then. <<== IllegalCast at MaintenanceWnd(

       'We found a maintenance window with the desired category, so show it.
        MaintenanceWnd(WhichWnd.MyMaintWnds(i)).Show
        Return

      End If
      
    End If
    
  End If
  
Next

Thoughts? Suggestions?

Thanks!

You need to use the Value of the WeakRef, so you’ll need to check that for nil too, and then cast the value

Ah yes, I’d forgotten that, and I didn’t see it in the documentation. Thank you for the quick catch!

I used a lot of WeakRefs in the web framework.

Wouldn’t a NilObjectException be more helpful in this situation? (I’m sure this has been discussed before and there’s probably a good reason.)