I personally believe that providing params keywords to achieve variable number of methods is a major advantage of C# syntax. In the method parameter list, the params keyword is added before the parameter of the array type, which can usually make the code more refined when calling the method.
For example, the following code:
class Program { static void Main(string[] args) { (Sum(1)); (Sum(1, 2, 3)); (Sum(1, 2, 3, 4, 5)); (); } private static int Sum(params int[] values) { int sum = 0; foreach (int value in values) sum += value; return sum; } }
Implement a Sum method to receive a set of integers and return their sums. After the parameter values are added with the params keyword, each element in this set of integers can be listed in the actual parameter list when called, which is very convenient.
Regarding the usage of the params keyword, the following points need to be paid attention to:
1. params can only be used for one-dimensional arrays, not multidimensional arrays and any collection types similar to arrays such as ArrayList, List<T>, etc.
2. The formal parameter that is added with the params keyword must be the last formal parameter in the parameter list, and only one params keyword is allowed in the method declaration.
3. There are four ways to use the params keyword:
The first type lists the elements of the array: Sum(1,2,3), which is also the most commonly used form;
The second type is to use the array name as the actual parameter like the array parameter without adding the params keyword: Sum(new int[]{1,2,3}) or int n=new int[]{1,2,3};Sum(n);;
The third way, adding the params keyword parameters can be omitted when called: Sum();//Return 0; this method can sometimes define one less method overload, but when overloading int Sum() is clearly defined, the compiler will give priority to int Sum() instead of Sum(params int[] values). Moreover, the params-type parameters are omitted, and an array with 0 elements will still be new inside the method, and the efficiency will be checked briefly.
The fourth type is not omitted to params-type parameters and replaced with null, which is slightly more efficient than the third type because it does not have new array inside.