The following Code throws the InvalidCastException error. What I wish to know is why and what the standard workaround is for this situation.
What I would like is the line B = C to work without me having to know what type of object C currently is. I need to find a way to get this to work so that i can finish a function I ma working on so that it will excecute correctly on any new object which implements the interface and boasts an Operator CType function to cast it to the type used in the function.Code:Module Module1 Interface IFooBar End Interface Class Foo : Implements IFooBar Public Shared Widening Operator CType(ByVal Val As Foo) As Bar Return New Bar End Operator End Class Class Bar : Implements IFooBar Public Shared Widening Operator CType(ByVal Val As Bar) As Foo Return New Foo End Operator End Class Sub Main() Dim A As Foo = New Foo Dim B As Bar = New Bar Dim C As IFooBar 'these assignments work fine with implicit casting A = B B = A C = A 'InvalidCastException Thrown Here B = C 'this throws the same error B = CType(C, Bar) 'this does not fail but requires pre-compile knowledge of the type of object in C B = CType(CType(C, Foo), Bar) End Sub End Module
I have been searching a while for a solution but I couldn't find one. It may be that I am missing a key term which would get me straight to the answer. Any help you can give me would be much appreciated. Although I would particularly appreciate some references to articles which might explain this problem and why it occurs as I am just learning Visual Basic.




Reply With Quote