Skip to main content

Parameter array and keyword params

In all the previous examples, we used a constant number of parameters. But by using the params keyword, we can pass an undefined 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 itself with the keyword params when defining the method must represent a one-dimensional array of the type whose data we are going to use. When calling the method, we can pass both single values and an array of values in place of the parameter with the params modifier, or we can pass no parameters at all. The number of values passed to the method is undefined, but all these values must correspond to the type of the parameter with params.

If we need to pass any other parameters, they must be specified before the parameter with the params keyword:

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); // the number 10 is passed to the initialValue parameter
Sum(1, 2, 3, 4);
Sum(1, 2, 3);
Sum(20);

Here, the Sum method has a mandatory parameter initialValue, so when calling the method, you must pass a value for it. Therefore, the first value when calling the method will be passed to this parameter.

However, after the parameter with the params modifier we can NOT 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 method of passing parameters must 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); // you can't do this - we need to pass an array.

Since the Sum method accepts an array without the params keyword as a parameter, we must pass an array as the first parameter when calling it. Besides, unlike the method with params parameter, other parameters can be placed after the array parameter.