This post originated from an RSS feed registered with .NET Buzz
by Paul Vick.
Original Post: For Each and Option Strict
Feed Title: Panopticon Central
Feed URL: /error.aspx?aspxerrorpath=/rss.aspx
Feed Description: a blog on Visual Basic, .NET and other stuff
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.