I am trying to implement the Strategy design pattern using interfaces.
However, while developing some code I stumbled upon something strange.
The type of the object is not verified in design-time.
Observe the following code.
Notice that Foo implements IFoo and Bar DOES NOT implement this interface.
No error is shown when trying this:
Dim fb2 As FooBar = New FooBar(bar)
The full code:
Module Module1
Sub Main()
Try
Dim foo As Foo = New Foo()
Dim bar As Bar = New Bar()
Dim fb1 As FooBar = New FooBar(foo)
fb1.DoIt()
Dim fb2 As FooBar = New FooBar(bar)
fb2.DoIt()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Sub
End Module
Public Class FooBar
Private _f As IFoo
Public Sub New(ByVal f As IFoo)
_f = f
End Sub
Public Sub DoIt()
_f.DoSomething()
End Sub
End Class
Public Interface IFoo
Sub DoSomething()
End Interface
Public Class Foo
Implements IFoo
Public Sub DoSomething() Implements IFoo.DoSomething
Console.WriteLine("DoSomething() called in Foo")
End Sub
End Class
Public Class Bar
Public Sub DoSomething()
Console.WriteLine("DoSomething() called in Bar")
End Sub
End Class
This code compiles fine. No error is shown in Visual Studio.
However, when I run this piece of code, I receive an InvalidCastException.
The output of the console:
DoSomething() called in Foo
Unable to cast object of type 'InterfaceTest.Bar' to type 'InterfaceTest.IFoo'.
Can anyone explain this behavior?
Turn on Option strict in the project properties.