The ref and out keywords are often used to change the behavior of parameters in a method. However, there’s a keyword that is much less known, but which is quite helpful: params. When using params, before any parameter declaration, it will allow us to provide a variable number of arguments when calling the method. The parameter using the params keyword contains the restriction that it has to be declared as an array.
To exemplify the usage of this type of argument, let’s declare a method that will sum all the terms provided in the call to the method.
As we can see, we are receiving an integer array of terms, and in the implementation we are iterating through it to get the sum of all the numbers provided. In the following code we are calling the method three times with different arguments.
In the first call, we provided one argument; we might as well send zero arguments i.e. an empty array. In the second call we used three arguments separated by commas. In the third call we sent an array of terms. These are the possible ways to call a method with a parameter using the params keyword. The output for these calls is the following:
The usage of the params keyword is bounded to the following conditions:
- Only one parameter can have this keyword
- This parameter must be the last in the formal parameters list
For part three we will see in detail how to define and use extension methods.