Parameter array and params keyword
In all previous examples, we used a fixed number of parameters. But by using the keyword params, we can pass an indefinite number of parameters:
void Sum(params int[] numbers)
{
int result = 0;
foreach (var n in numbers)
{
result += n;
}
Console.WriteLine(result);
}
int[] nums = { 1, 2, 3, 4, 5 };
Sum(nums);
Sum(1, 2, 3, 4);
Sum(1, 2, 3);
Sum();
The parameter with the keyword params in the method definition must be a one-dimensional array of the type of data we want to use. When calling the method, in place of the parameter with the params modifier, we can pass either individual values, or an array of values, or even no parameters at all. The number of values passed to the method is undefined, but all these values must match the type of the parameter with params.
If we need to pass some other parameters, they must be specified before the parameter with the keyword params:
void Sum(int initialValue, params int[] numbers)
{
int result = initialValue;
foreach (var n in numbers)
{
result += n;
}
Console.WriteLine(result);
}
int[] nums = { 1, 2, 3, 4, 5 };
Sum(10, nums); // number 10 is passed to parameter initialValue
Sum(1, 2, 3, 4);
Sum(1, 2, 3);
Sum(20);
Here the method Sum has a required parameter initialValue, so when calling the method a value must be passed for it. Therefore, the first value passed during the method call is assigned to this parameter.
However, after the parameter with the params modifier, we cannot specify other parameters. That is, the following method definition is invalid:
// This does NOT work
void Sum(params int[] numbers, int initialValue)
{}
Array as a parameter
Also, this way of passing parameters should be distinguished from passing an array as a parameter:
void Sum(int[] numbers, int initialValue)
{
int result = initialValue;
foreach (var n in numbers)
{
result += n;
}
Console.WriteLine(result);
}
int[] nums = { 1, 2, 3, 4, 5 };
Sum(nums, 10);
// Sum(1, 2, 3, 4); // this is not allowed — we must pass an array
Since the method Sum takes an array as a parameter without the params keyword, when calling it we must necessarily pass an array as the first argument. In addition, unlike the method with a params parameter, other parameters can be placed after the array parameter.