Casting arrays that works on watch and command window but not in code.
My application is casting arrays in a way it should work. To test if I
was doing something invalid, I wrote a test code that has similar
structure of the classes in my application. The test worked fine, the
casting I want to do must work. I compared the structure of the test
with the application to ensure they where similar (inheriting twice,
base class implements interface,…).
If I break the application at the line it is generating the cast
exception, I am able to do the following:
In the watch window: cast the array. Works as expected.
In the command window: cast the array, get first element and print the
value of a property. Works ok.
I do not understand what is going on. At this stage, I have one
question:
if something works in the command window and in the watch window
should it work in Code?
I am using in the command window:
? DirectCast(inte rfaceParameters , BaseClass())(0) .AnyStringPrope rty.
works ok.
I am using in the watch window:
DirectCast(inte rfaceParameters , BaseClass()). works ok.
====Test code with the same structure of the Application Code========
Option Strict On
Interface IMainInterface : Sub MainImplement() : End Interface
Class BaseClass : Implements IMainInterface
Public Sub MainImplement() Implements IMainInterface. MainImplement
End Sub
End Class
Class FirstDerivedCla ss : Inherits BaseClass : End Class
Class SecondDerivedCl ass : Inherits FirstDerivedCla ss : End Class
Module Test2
Sub Main()
'array of derived classes (two levels of inheritance)
Dim Seconds() As SecondDerivedCl ass = _
New SecondDerivedCl ass() {New SecondDerivedCl ass}
SubWithInterfac eParameters(Sec onds)
End Sub
Sub SubWithInterfac eParameters(ByV al interfaceParame ters() As
IMainInterface)
‘this line is the one that generates casting exception
'in my application. It worksfine with this test.
'The casting works in watch and command windows
'in the application
Dim bases() As BaseClass = _
DirectCast(inte rfaceParameters , BaseClass())
End Sub
End Module