Section 8.11. Variable-Length Parameter Lists


8.11. Variable-Length Parameter Lists

It is possible to create methods that receive a variable number of arguments, using keyword ParamArray. The program in Fig. 8.19 calls programmer-defined method AnyNumberOfArguments three times, passing a different number of values each time. The values passed into method AnyNumberOfArguments are stored in one-dimensional Integer array array1, which is declared using ParamArray.

Figure 8.19. Creating variable-length parameter lists.

  1  ' Fig. 8.19: ParamArrayTest.vb  2  ' Using ParamArray to create variable-length parameter lists.  3  Module ParamArrayTest  4     Sub Main()  5        AnyNumberOfArguments()  6        AnyNumberOfArguments(2, 3)  7        AnyNumberOfArguments(7, 8, 9, 10, 11, 12)  8     End Sub ' Main  9 10     ' receives any number of arguments in array 11     Sub AnyNumberOf Arguments(ByVal ParamArray array1 As Integer()) 12        Dim total As Integer = 0 13 14        ' check number of arguments 15        If array1.Length = 0 Then 16           Console.WriteLine("Method AnyNumberOfArguments"&_ 17              "received 0 arguments.") 18        Else 19           Console.Write("The total of") 20 21           'total array elements 22           For i As Integer = 0 To array1.GetUpperBound(0) 23              Console.Write(array1(i) & " ") 24              total+=array1(i) 25           Next 26 27           Console.WriteLine("is {0}.", total) 28        End If 29     End Sub 'AnyNumberOfArguments 30  End Module 'ParamArrayTest 

 Method AnyNumberOfArguments received 0 arguments. The total of 2 3 is 5. The total of 7 8 9 10 11 12 is 57. 



We call method AnyNumberOfArguments in lines 57, passing a different number of arguments each time. The method is defined in lines 1129 and applies keyword ParamArray to array1 in line 11. The If statement in lines 1528 determines whether the number of arguments passed to the method is zero. If not, lines 1927 display array1's elements and their sum. All arguments passed to the ParamArray array must be of the same type as the array or a type that can be implicitly converted to the type of the array, otherwise a compilation error occurs (when Option Strict is On). Though we used an Integer array in this example, any type of array can be used.

In the last chapter, we discussed method overloading. Programmers often prefer to use method overloading rather than write methods with variable-length parameter lists.

Common Programming Error 8.5

Attempting to declare a parameter variable to the right of the ParamArray array variable is a syntax error.


Common Programming Error 8.6

Using ByRef with ParamArray is a syntax error.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net