Visual Studio seems to stop type checking function parameters when one of the parameters is an interface.
Consider the following:
' An interface and the class that implements it:
Public Interface IA
End Interface
Public Class A
Implements IA
End Class
' Another reference type for the demonstration:
Public Class MyReferenceType
End Class
' A function that uses IA as the type of one of its parameters:
Private Function SomeFunc(ByVal a As IA, ByVal r As MyReferenceType)
Return Nothing
End Sub
And here is an example of the type checking problems:
Private Sub Example()
Dim a As IA = New A
Dim r As New MyReferenceType
' Some other random reference type, choose any
' other reference type you like
Dim list As New List(Of String)
' Each of these calls to SomeFunc compile without errors.
SomeFunc(r, r)
SomeFunc(r, a)
SomeFunc(list, r)
SomeFunc(list, a)
' Does not compile due to type mismatch
'SomeFunc(list, list)
End Sub
As my comments suggest, this code compiles fine, with no errors in the editor either. If I execute the program though I get System.InvalidCastException
, which isn't a surprise at all. I guess this is a type checking bug in the compiler? I'm using Visual Studio 2005, so is this fixed in a later version of VS?
I believe it's because you've got Option Strict off. If you turn Option Strict on to start with, your code fails to compile, exactly as we'd expect.
Note that this:
SomeFunc(list, a)
is not like this:
SomeFunc(list, list)
In the first case, when Option Strict is off, the compiler is effectively inserting a cast for you. After all, a value of type IA
can be a MyReferenceType
.
In the second case, a value of List(Of String)
cannot ever be compatible with MyReferenceType
(with the arguable exception of a value of Nothing
...), so even with Option Strict off, compilation fails. The compiler won't let you try something which can't ever work.
Moral of the story: for better type checking, turn Option Strict on.