For Each and Option Strict

Duncan pointed me to a thread on GotDotNet that asked a frequently asked question: why doesn’t For Each require a cast when Option Strict is on? For example, the following code is entirely legal:

Option Strict On

Sub Foo(ByVal array() As Long)
    For Each i As Integer In array
    Next i
End Sub

As For Each iterates through the array, each element of the array is automatically cast from Long down to Integer without comment, even though Option Strict usually requires an explicit cast. Why is that? Mostly for developer convenience with dealing with collections such as Collection or Arraylist. In those cases, the element type of the collection is always Object. If we required a cast to iterate through a collection of Object values, where would you put the cast? There’s no place to actually do the cast in the For Each statement, so you’d be stuck having to have your iterator variable be typed as Object and then doing the cast yourself into anoher variable:

Option Strict On

Sub Foo(ByVal array As ArrayList)
    For Each o As Object In array
        Dim i As Integer = CInt(o)
    Next i
End Sub

Since ArrayList/Collection object tend to have the same type in them and people iterate through them a lot, we decided that it made more sense to bend the rules in this case and do the cast automatically for you. (You can thank us later.) As an interesting side-note, C# does exactly the same thing in their foreach statement.

9 thoughts on “For Each and Option Strict”

  1. Pingback: Panopticon Central
  2. Okay, so the real reason is that works (which I always wondered about) because you didn’t have generics in the 1.x framework. Got it.

  3. I think foreach is slower because it makes a copy of the value to a local variable…There’s also something with foreach locking (readonly) the (some?) collection …but not too sure on that last point.

    Also foreach works differently against arrays then it does against collections…I think the performance penalty only comes when dealing with collections…the compiler will turn a foreach on an array into a ‘regualr’ for.

    i could be wrong on all of this 😉

  4. Pingback: Anonymous
  5. Pingback: Anonymous
  6. Pingback: Mabsterama
  7. Pingback: Anonymous

Leave a Reply