C# params Keyword
The C# params keyword permits you to pass any variety of arguments that has an equivalent knowledge sort so store them into one single array parameter. The code below demonstrates the way to use the C# params keyword.
using System;
namespace ParamsKeywordDemo
{
public class Program
{
static int CalculateSum(params int[] numbers)
{
int total = 0;
foreach (int number in numbers)
{
total += number;
}
return total;
}
public static void Main()
{
Console.WriteLine("1 + 2 + 3 = {0}", CalculateSum(1, 2, 3));
Console.WriteLine("1 + 2 + 3 + 4 = {0}", CalculateSum(1, 2, 3, 4));
Console.WriteLine("1 + 2 + 3 + 4 + 5 = {0}", CalculateSum(1, 2, 3, 4, 5));
}
}
}
Example 1 – Using the params Keyword
1 + 2 + 3 = 6 1 + 2 + 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15
We used the params keyword before the data type of the array parameter. We then called the method three times supplying a different number of arguments. These arguments are stored inside the array parameter. Using a foreach loop (line 11-14), the sum of all the elements is determined and returned to the caller.
When you have multiple parameters in a method, you can only have one parameter that is labeled with params. This parameter labeled with params should be placed in the last position of the parameter list. If it is not in the last position or there are more than one paramsparameter, an error will occur. The three method headers below shows you which is right and which are wrong.
void SomeFunction(params int[] x, params int[] y) //ERROR
void SomeFunction(params int[] x, int y, int z) //ERROR
void SomeFunction(int x, int y, params int[] z) //Correct