SHORT ANSWEAR: there is no way to prevent this
Maybe this question is duplicated, but I didnt find any solutions because I dont know what words should I search for:
Option Strict On
Option Explicit On
Public Class Fruit
'... stuff
End Class
Public Class Apple
Inherits Fruit
'... stuff
End Class
Public Class FruitCart
Private _fruits As New List(Of Fruit)
Public Function GetFirstApple() As Apple
Return Me._fruits(0) '... <-- Option Strict error
End Function
Public Function GetApples() As List(Of Apple)
Dim result As New List(Of Apple)
For Each A As Apple In Me._fruits '... Why no error?
result.Add(A)
Next
Return result
End Function
End Class
The method GetFirstApple() gives me a compile error. This is the behavior I want. The method GetApples() dont give me a compile error, leading to run-time error.
Why the compiler allows the casting on the For Each, even with Option Strict On? I want the compiler to give me a compile error on the GetApples() method.
CodePudding user response:
I just found it out. There is no way to prevent this, as documented on the "Narrowing conversions" on the For Each page: