The Artima Developer Community
Sponsored Link

.NET Buzz Forum
For Each and Option Strict

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Paul Vick

Posts: 783
Nickname: paulv
Registered: Aug, 2003

Paul Vick is a Tech Lead on Visual Basic at Microsoft Corp.
For Each and Option Strict Posted: Jun 9, 2004 9:42 AM
Reply to this message Reply

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
Latest .NET Buzz Posts
Latest .NET Buzz Posts by Paul Vick
Latest Posts From Panopticon Central

Advertisement

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.

Read: For Each and Option Strict

Topic: Venus Transit on the Web Previous Topic   Next Topic Topic: Solar Eclipse of a different kind

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use