|
An ordinary VB developer shares his own successes and failures |
|
| Home News Articles Resources Tips Downloads About me | ||
For i As Integer...Declare loop indexes inline within the For statement.I just want to remind you of one cool VB.NET language feature introduced with VB.NET 2003 - the ability to declare loop indexes in theFor statement:
For i As Integer = 0 to MyArray.Length - 1 MyArray(i) = i NextThis is how the above loop should have been written before: Dim i As Integer For i = 0 to MyArray.Length - 1 MyArray(i) = i NextYou might think it's not a big deal - you only save one line of code. That's true, but it's more elegant and it prevents you to misuse the loop indexes outside of the loop. This is because the declared loop index's scope is restricted just to the loop's body. The following code would generate a compile-time error:
Class Demo
Shared Sub Test()
For i As Integer = 0 To 10
Debug.WriteLine(i.ToString())
Next
Debug.WriteLine(i.ToString()) ' << Compiler error here!
End Sub
End Class
And, by the way, you can use the inline loop declaration with
the For Each statement as well:
For Each f As FontFamily In FontFamily.Families Debug.WriteLine(f.Name) NextNice! |
||
|
|
||
| ©2003-2007 Palo Mraz. All Rights Reserved. See my 'new browser window' policy | ||