Previous | Index | Next 

[PRB] Passing a ParamArray to another method

Consider the following VB6 code:

    Sub Main()
        One "abc"
    End Sub
    
    Private Sub One(ParamArray args() As Variant)
        Debug.Print args(0)          ' => displays "abc"
        Two args  
    End Function

    Private Sub Two(ParamArray args() As Variant)
        Debug.Print args(0)(0)       ' => displays "abc"
        Three args
    End Function

    Private Sub Three(ParamArray args() As Variant)
        Debug.Print args(0)(0)(0)    ' => displays "abc"
    End Function

The remarks in code make it clear that the args ParamArray in method One is passed into the first element of the args ParamArray in method Two, and the args ParamArray in method Two is passed in the first element of the args ParamArray in method Three.

Let’s consider now a similar code snippet in VB.NET:

    Sub Main()
        One("abc")
    End Sub
    
    Private Sub One(ParamArray args() As Object)
        Debug.Print(args(0))          ' => displays "abc"
        Two(args)
    End Function

    Private Sub Two(ParamArray args() As Object)
        Debug.Print(args(0))          ' => displays "abc"
        Three(args)
    End Function

    Private Sub Three(ParamArray args() As Object)
        Debug.Print(args(0))          ' => displays "abc"
    End Function

The remarks in the VB.NET code suggest that the args ParamArray in method One is passed into the args ParamArray in method Two, which in turn is passed in the args ParamArray in method Three. In other words, the original args array is passed along to all methods in the call chain.

VB Migration Partner can’t compensate for this important difference between VB6 and VB.NET. If the original piece of VB6 code is migrated, then the converted VB.NET code is likely to throw either compilation or runtime errors. For example, you have a compilation error if the call statement includes additional arguments, as in:

    Private Sub Two(ParamArray args() As Object)
        Debug.Print(args(0))          ' => displays "abc"
        Three(args, "def")            ' => compilation error
    End Function

The simplest way to avoid compilation errors and reproduce the VB6 behavior is to manually create the array passed to further methods in the call chain, as in this example:

    Sub Main()
        One("abc")
    End Sub
    
    Private Sub One(ParamArray args() As Object)
        Debug.Print(args(0))          ' => displays "abc"
        Dim tempArr() As Object = {args}
        Two(tempArr)
    End Function

    Private Sub Two(ParamArray args() As Object)
        Debug.Print(args(0)(0))       ' => displays "abc"
        Dim tempArr() As Object = {args, "def"}
        Three(tempArr)
    End Function

    Private Sub Three(ParamArray args() As Object)
        Debug.Print(args(0)(0)(0))   ' => displays "abc"
    End Function

        

 

Previous | Index | Next