Illegal Cast Mystery

I have a user who encountered an Illegal Cast exception in this code, and I can’t figure out why it would happen. This code is in App.Activate, and there were two windows open when this exception was raised. One was a DisplayWnd, the other was a CountWnd, and they’re not related except that both might reference the same Info object.

Does anyone have any suggestions for possible scenarios that could cause this exception?

Here’s the code in App.Activate:

dim x as integer
dim ThisInfo as Info

if WindowCount>0 then

for x=WindowCount-1 downto 0
  if Window(x)<>nil then
    if Window(x) isa DisplayWnd then                             'DisplayWnd is a document-type window
      if DisplayWnd(Window(x)).Closing=False then       '.Closing is a property of DisplayWnd class, it is set when the window's CancelClose event is raised
        if DisplayWnd(Window(x)).MyInfo<>nil then        '.MyInfo is a property of DisplayWnd
          if DisplayWnd(Window(x)).Closing=False then    <========= ILLEGAL CAST EXCEPTION IS RAISED HERE


I can simply put a try/catch around the center of the code to solve the immediate problem, but I’d like to understand why this exception would ever be raised.


  • John

Does this happen every time or sporadically?

What’s the full message of the Exception? Click the exception in the debugger and it’ll say “TypeA cannot be cast to TypeB”.

I don’t know if it’s possible, this is a long shot, but Window(x) is a function and maybe returns a different window there. Try grabbing the result of that function once and test it so there’s no possibility it switches underneath you

[code]for x=WindowCount-1 downto 0

dim w As Window = Window(x)

if w <> nil then

if w isa DisplayWnd then

  if DisplayWnd(w).Closing=False then


I agree with Will. The value of Window(x) is probably changing underneath you. It could happen if the other window gets focus somehow (like if the user clicked on it while your code is running). Use a temporary variable to store it as Will demonstrates. The order of the contents of Window() is fluid.

It can also change if Windows are created or destroyed and since you’re checking if the window is in the middle of closing, that would be my instinct. Make a reference instead of using Window(x) every time and this will probably stop.