params
allows a method parameter to receive a variable number of arguments, i.e. zero, one or multiple arguments are allowed for that parameter.
static int AddAll(params int[] numbers)
{
int total = 0;
foreach (int number in numbers)
{
total += number;
}
return total;
}
This method can now be called with a typical list of int
arguments, or an array of ints.
AddAll(5, 10, 15, 20); // 50
AddAll(new int[] { 5, 10, 15, 20 }); // 50
params
must appear at most once and if used, it must be last in the argument list, even if the succeeding type is different to that of the array.
Be careful when overloading functions when using the params
keyword. C# prefers matching more specific overloads before resorting to trying to use overloads with params
. For example if you have two methods:
static double Add(params double[] numbers)
{
Console.WriteLine("Add with array of doubles");
double total = 0.0;
foreach (double number in numbers)
{
total += number;
}
return total;
}
static int Add(int a, int b)
{
Console.WriteLine("Add with 2 ints");
return a + b;
}
Then the specific 2 argument overload will take precedence before trying the params
overload.
Add(2, 3); //prints "Add with 2 ints"
Add(2, 3.0); //prints "Add with array of doubles" (doubles are not ints)
Add(2, 3, 4); //prints "Add with array of doubles" (no 3 argument overload)