Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are interfaces not strongly typed?

I have the following code compiles without issue. Of course, I get an invalid cast exception when executing the Dim C As IDoThingsC = GetThing_C(). Am I missing something? Would you ever want to return an object that does not meet the interface requirement for a function return value?

Public Class ClassA

  Public Sub DoThings_A()
    Debug.Print("Doing A things...")
  End Sub

End Class


Public Class ClassB
  Implements IDoThingsC

  Public Sub DoThings_B()
    Debug.Print("Doing B things...")
  End Sub

  Public Sub DoThings_C() Implements IDoThingsC.DoThings_C
    Debug.Print("Doing C things...")
  End Sub

End Class


Public Interface IDoThingsC

  Sub DoThings_C()

End Interface


Public Class aTest

  Public Sub Test()

    Dim C As IDoThingsC = GetThing_C()
    C.DoThings_C()

  End Sub


  Public Function GetThing_C() As IDoThingsC

    Dim Thing As ClassA = New ClassA
    Thing.DoThings_A()

    Return Thing

  End Function


End Class
like image 727
JRS Avatar asked Dec 10 '22 17:12

JRS


1 Answers

Use Option Strict On at the top of your source code file to catch problems like this. You'll get a compile time error instead of a runtime error:

error BC30512: Option Strict On disallows implicit conversions from 'ClassA' to 'IDoThingsC'.
like image 110
Hans Passant Avatar answered Jan 02 '23 23:01

Hans Passant