Controlling Variables in For Loops

The For and For Each loops let you define their controlling variable as a block variable, using this syntax:

For i As Integer = 1 To 10


This syntax was introduced in Visual Studio.NET 2003. Many books and articles, however, continue to use the old syntax:

Dim i As Integer
For i = 1 To 10

The new syntax is preferred in all cases because it prevents you from accidentally reusing the value of the controlling variable when the loop exited, which is considered a programming mistake and a potential source of bugs.

Close Bitnami banner