For in Visual Basic .NET

Imports System

Module ForLoops
    Sub Main()
        ' The most basic type, with a single condition.
        Dim i As Integer = 1
        While i <= 3
            Console.WriteLine(i)
            i += 1
        End While

        ' A classic initial/condition/after For loop.
        For j As Integer = 0 To 2
            Console.WriteLine(j)
        Next

        ' Another way of accomplishing the basic "do this
        ' N times" iteration is using a For Each loop.
        For Each index As Integer In Enumerable.Range(0, 3)
            Console.WriteLine($"range {index}")
        Next

        ' While True will loop repeatedly
        ' until you Exit While or Return from
        ' the enclosing function.
        While True
            Console.WriteLine("loop")
            Exit While
        End While

        ' You can also Continue to the next iteration of
        ' the loop.
        For Each n As Integer In Enumerable.Range(0, 6)
            If n Mod 2 = 0 Then
                Continue For
            End If
            Console.WriteLine(n)
        Next
    End Sub
End Module

In Visual Basic .NET, we use different looping constructs to achieve similar functionality to the original example:

  1. The basic condition-only loop is implemented using a While loop.

  2. The classic three-part loop is implemented using a For loop with a To clause.

  3. The range-based loop is implemented using a For Each loop with Enumerable.Range.

  4. The infinite loop is implemented using While True with an Exit While statement to break out of it.

  5. The continue functionality is achieved using Continue For within a For Each loop.

To run this program, save it as ForLoops.vb and compile it using the Visual Basic compiler:

$ vbc ForLoops.vb
$ mono ForLoops.exe
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Visual Basic .NET provides various looping constructs that can be used in different scenarios. The For loop is commonly used when you know the number of iterations in advance, while While and Do loops are used when the number of iterations is not known beforehand. The For Each loop is particularly useful for iterating over collections or ranges.