C# Params: What It Is and How to Use It
In C#, params is a parameter modifier used to indicate a variable-length parameter array, allowing a method to accept a varying number of parameters.
When an array parameter is marked with the params qualifier in the method’s parameter list, you can pass any number of parameter values when calling the method, and these values will automatically be packaged into an array.
The main functions of parameters are twofold:
- Simplify method calls: Using the params modifier can make method calls more succinct, eliminating the need to manually create arrays and pass parameters, as multiple parameter values can be passed directly.
- Handling variable number of parameters: the params modifier allows a method to accept an indefinite number of parameters, and enables the method to process any number of parameter values passed to it, similar to handling an array within the method.
For example, here is a sample using the params modifier:
public void PrintNumbers(params int[] numbers)
{
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
// 调用方法时可以传递任意数量的参数值
PrintNumbers(1, 2, 3);
PrintNumbers(4, 5, 6, 7);
In the example above, the PrintNumbers method accepts a variable-length int array parameter. When calling this method, you can pass any number of argument values, which will be encapsulated into an int array. The method internally uses a foreach loop to iterate and print each parameter value.