This keyword is used before the parameter type in the method signature. Here is an example to illustrate how variadic parameters work in C#:
Example of Variadic Parameters in C#
|
|
Explanation
We start with the Method Declaration:
|
|
The params
keyword allows the method to accept a variable number of integer arguments. These arguments are treated as an array within the method.
Then, we use the parameter like this:
|
|
The method iterates through the numbers
array, summing up all the values.
Let’s take usage examples:
|
|
The method Sum
is called with different numbers of arguments. The params
keyword allows the method to handle these calls gracefully.
Type Checking
Naturally, the parameters must all match the type on the variadic parameters. At least, in C#, it’s the case.
However, this isn’t true for all languages: for example, if you use plain JavaScript, you can use variadic parameters through the spread operator (...numbers
) if you use modern JavaScript.
|
|
It replaced the use of the implicit arguments
variable.
Consequently, if you had the following code:
|
|
You would get this output:
|
|
To solve that issue (unless you really need that behavior), using TypeScript’s static typing bring the C# strength:
|
|
Why Use Variadic Parameters
Variadic parameters simplify the method signature and makes the code more flexible and easier to maintain, avoiding method signature proliferation for different numbers of parameters.
Have you ever used variadic parameters? Maybe, today, you’ll find code where you could apply the programming feature.
Did you learn something?
Follow me
If so, make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.
Thanks for reading this article