C # parameter array
Sometimes, when you declare a method, you cannot determine the number of parameters to pass to the function as arguments. The C # parameter array solves this problem, which is usually used to pass an unknown number of arguments to the function.
Params keyword
When using arrays as formal parameters, C # provides params
keyword, which allows you to pass either an array argument or an array of elements when calling a method with an array of formal parameters. params
format of the use is:
Public return type method name (params type name [] array name)
Example
The following example shows how to use a parameter array:
Example
using System;
namespace ArrayApplication
{
class ParamArray
{
public int AddElements(params int[] arr)
{
int sum = 0;
foreach (int i in arr)
{
sum += i;
}
return sum;
}
}
class TestClass
{
static void Main(string[] args)
{
ParamArray app = new ParamArray();
int sum = app.AddElements(512, 720, 250, 567, 889);
Console.WriteLine("The total is: {0}", sum);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following results:
The total is: 2938