Variable declaration inside of loops (VB.NET 2003)

A nice language improvement in VB.NET 2003, is that you can declare variables inside a loop. For example, if I wanted to construct a For Each loop in VB.NET 2002 I would have to do it like this:
Dim item As Customer
For Each item In CustomerCollection
    ' Do Stuff
Next

In VB.NET 2003, you can do it like this:
For Each item As Customer In CustomerCollection
    ' Do Stuff
Next

It's only 1 line shorter, but in my humble opinion, it's a very nice improvement.

2 Comments

  • So would the loop variable still be valid after the loop completes, or is the variable out-of-scope outside the loop?





    For Each item As Customer In CustomerCollection


    ' Do Stuff


    Next





    Is item valid here?





    Also, what if the outer scope also has an item variable, like this? Would this be a compile-time error?





    Dim item As Integer


    ' Do Some Stuff





    For Each item As Customer In CustomerCollection


    ' Do Stuff


    Next


  • Hi Jan,

    can you please leave some example on how to nest
    For Each item in itemCollection Loop

    It will be of great help.

Comments have been disabled for this content.