Note that there are some explanatory texts on larger screens.

plurals
  1. PO.NET type check on interface
    primarykey
    data
    text
    <p>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.</p> <p>Observe the following code. Notice that Foo implements IFoo and Bar DOES NOT implement this interface. No error is shown when trying this:</p> <pre><code>Dim fb2 As FooBar = New FooBar(bar) </code></pre> <p>The full code:</p> <pre><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 </code></pre> <p>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:</p> <pre><code>DoSomething() called in Foo Unable to cast object of type 'InterfaceTest.Bar' to type 'InterfaceTest.IFoo'. </code></pre> <p>Can anyone explain this behavior?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload