Variable-length argument lists allow you to create methods that receive an arbitrary number of arguments. A one-dimensional array-type argument preceded by the keyword params
in a method’s parameter list indicates that the method receives a variable number of arguments with the type of the array’s elements. This use of a params
modifier can occur only in the parameter list’s last parameter. While you can use method overloading and array passing to accomplish much of what is accomplished with variable-length argument lists, using the params
modifier is more concise.
Figure 8.23 demonstrates method Average
(lines 8–19), which receives a variable-length sequence of double
s (line 8). C# treats the variable-length argument list as a one-dimensional array whose elements are all of the same type. Hence, the method body can manipulate the parameter numbers
as an array of double
s. Lines 13–16 use the foreach
loop to walk through the array and calculate the total of the double
s in the array. Line 18 accesses numbers.Length
to obtain the size of the numbers
array for use in the averaging calculation. Lines 30, 32 and 34 in Main
call method Average
with two, three and four arguments, respectively. Method Average
has a variable-length argument list, so it can average as many double
arguments as the caller passes. The output reveals that each call to method Average
returns the correct value.
The params
modifier may be used only with the last parameter of the parameter list.