8.11. Variable-Length Parameter ListsIt 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.
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
Common Programming Error 8.6
|