Previous | Index | Next 

[HOWTO] Move the declaration of a variable into a For or For Each loop

Note: this article only applies to conversions to VB.NET.

VB6 requires that controlling variables in For and For Each loops to be defined before the loop is entered, as in this typical code snippet:

        Dim ctrl As control
        For Each ctrl In Form1.controls
           ' ...
        Next


If the ctrl variable isn’t used outside the loop, you might want to move the variable declaration inside the loop when you convert the code to VB.NET:

        For Each ctrl As Control In Form1.controls
            ' ...
        Next


VB Migration Partner doesn’t perform this replacement automatically. However, you can use a PostProcess pragma to do the replacement yourself:

        '## PostProcess "Dim (?<name>\w+) As (?<type>\w+)( = .+?)\n\s+For Each \k In", 
		"For Each ${name} As ${type} In"


The pattern used for standard For loops is slightly different:

        '## PostProcess "Dim (?<name>\w+) As (?<type>\w+)( = .+?)\n\s+For \k =", 
		"For ${name} As ${type} ="


Assuming the both pragmas are applied, then the following VB6 code:

        Dim s As String
        For Each s In myarray
            ' ...
        Next

        Dim i As Integer
        For i = 1 To 10
            ' ...
        Next


is translated to VB.NET as follows:

        For Each s As String In myarray
            ' ...
        Next
    
        For i As Short = 1 To 10
            ' ...
        Next


Notice that the search pattern accounts for initialized variables and assumes that the For Each loop follows immediately the Dim statement (empty lines are OK, though).
If the controlling variable is used after the Next keyword, then the VB.NET compiler emits a compilation error. You can take note of such errors, go back to the original VB6 code and add a statement – for example, a remark – between the Dim statement and the For or For Each statement, to have VB Migration Partner ignore that specific occurrence:

        Dim s As String
        ' Note that s variable shouldn’t be merged in following code
        For Each s In myarray
            ' ...
        Next
        ' reset the s variable
        s = ""

 

Previous | Index | Next