The number of formal parameters in C is variable with the params keyword

  • 2020-05-16 06:48:02
  • OfStack

For example, the following code:
 
class Program 
{ 
static void Main(string[] args) 
{ 
Console.WriteLine(Sum(1)); 
Console.WriteLine(Sum(1, 2, 3)); 
Console.WriteLine(Sum(1, 2, 3, 4, 5)); 
Console.ReadKey(); 
} 
private static int Sum(params int[] values) 
{ 
int sum = 0; 
foreach (int value in values) 
sum += value; 
return sum; 
} 
} 

An Sum method is implemented to receive a set of integers and return their sum. When the values parameter is appended with the params keyword, it is convenient to list each element in the set of integers in the argument list when invoked.
With regard to the usage of the params keyword, the following points need to be noted:
1. params can only be used for 1-dimensional arrays, not multi-dimensional arrays and things like ArrayList, List < T > Any type of collection that looks like an array.
2. The parameter to which the params keyword is added must be the last parameter in the parameter list, and only one params keyword is allowed in the method declaration.
3. Using the params keyword method, there are three call forms:
The first is to list the elements of the array: Sum(1,2,3), which is the most common form.
The second, like an array parameter without the params keyword, takes the array name as an argument: Sum(new int[]{1,2,3}) or int n=new int[]{1,2,3}; Sum (n); ;
Third, the parameters with the params keyword can be omitted when called: Sum(); // returns 0; This sometimes allows one less method overload to be defined, but when overloading int Sum() is explicitly defined, the compiler calls int Sum() in preference to Sum(params int[] values). Moreover, params type parameters are omitted, and an array with 0 element number will still be new1 inside the method, which will be slightly checked for efficiency.
The fourth, instead of omitting the params type parameter, USES null instead, which is slightly more efficient than the third, because it does not contain the new array.

Related articles: