C# params Keyword Explained

In C#, the params keyword is used to specify that a method parameter can accept a variable number of arguments. This means that the method can accept zero or more arguments, all of which must be of the same type.

The syntax for using the params keyword is as follows:

public void methodName(params dataType[] parameterName)
{
    // 方法体
}

Here is an example using the params keyword.

public void PrintNumbers(params int[] numbers)
{
    foreach (int num in numbers)
    {
        Console.WriteLine(num);
    }
}

// 调用方法
PrintNumbers(1, 2, 3, 4, 5);
PrintNumbers(10, 20);
PrintNumbers(); // 不传递任何参数

In the example above, the PrintNumbers method accepts a variable number of integer parameters and prints them on the console. By using the params keyword, we can pass any number of integer parameters during method invocation, even without passing any parameters.

It should be noted that the params keyword can only be used in the last parameter of a method, and each method can have at most one params parameter.

bannerAds