Export (0) Print
Expand All ParamArray Parameters

Visual Studio .NET 2003

ParamArray parameters are declared with the ParamArray modifier. If the ParamArray modifier is present, the ByVal modifier must be specified, and no other parameter may use the ParamArray modifier. The ParamArray parameter's type must be a one-dimensional array, and it must be the last parameter in the parameter list.

A ParamArray parameter represents an indeterminate number of parameters of the type of the ParamArray. Within the method itself, a ParamArray parameter is treated as its declared type and has no special semantics. A ParamArray parameter is implicitly optional, with a default value of an empty one-dimensional array of the type of the ParamArray.

A ParamArray permits arguments to be specified in one of two ways in a method invocation:

  • The argument given for a ParamArray can be a single expression of a type that widens to the ParamArray type. In this case, the ParamArray acts precisely like a value parameter.
  • Alternatively, the invocation can specify zero or more arguments for the ParamArray, where each argument is an expression of a type that is implicitly convertible to the element type of the ParamArray. In this case, the invocation creates an instance of the ParamArray type with a length corresponding to the number of arguments, initializes the elements of the array instance with the given argument values, and uses the newly created array instance as the actual argument.

Except for allowing a variable number of arguments in an invocation, a ParamArray is precisely equivalent to a value parameter of the same type, as the following example illustrates.

Imports System

Module Test
    Sub F(ByVal ParamArray args As Integer)
        Dim i As Integer

        Console.Write("Array contains " & args.Length & " elements:")
        For Each i In args
            Console.Write(" " & i)
        Next i
    End Sub

    Sub Main()
        Dim a As Integer() = { 1, 2, 3 }

        F(10, 20, 30, 40)
    End Sub
End Module

The example produces the output

Array contains 3 elements: 1 2 3
Array contains 4 elements: 10 20 30 40
Array contains 0 elements:

The first invocation of F simply passes the array a as a value parameter. The second invocation of F automatically creates a four-element array with the given element values and passes that array instance as a value parameter. Likewise, the third invocation of F creates a zero-element array and passes that instance as a value parameter. The second and third invocations are precisely equivalent to writing:

F(New Integer() {10, 20, 30, 40})
F(New Integer() {})

ParamArray parameters may not be specified in delegate or event declarations.

See Also Value Parameters | Reference Parameters | Optional Parameters | 9.2.2 External Method Declarations | 9.2.5 Method Parameters | ParamArray (Visual Basic Language Reference) | Parameter Arrays (Visual Basic Language Concepts)

© 2015 Microsoft