I know this is a basic question, but I couldn't find an answer.
Why use it? if you write a function or a method that's using it, when you remove it the code will still work perfectly, 100% as without it. E.g:
With params:
static public int addTwoEach(params int[] args) { int sum = 0; foreach (var item in args) sum += item + 2; return sum; }
Without params:
static public int addTwoEach(int[] args) { int sum = 0; foreach (var item in args) sum += item + 2; return sum; }
The "params" keyword in C# allows a method to accept a variable number of arguments. C# params works as an array of objects. By using params keyword in a method argument definition, we can pass a number of arguments.
What Does Parameter (param) Mean? A parameter is a special kind of variable in computer programming language that is used to pass information between functions or procedures. The actual information passed is called an argument.
Param is a library providing Parameters: Python attributes extended to have features such as type and range checking, dynamically generated values, documentation strings, default values, etc., each of which is inherited from parent classes if not specified in a subclass.
Parameters and Arguments Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. The following example has a method that takes a String called fname as parameter.
With params
you can call your method like this:
addTwoEach(1, 2, 3, 4, 5);
Without params
, you can’t.
Additionally, you can call the method with an array as a parameter in both cases:
addTwoEach(new int[] { 1, 2, 3, 4, 5 });
That is, params
allows you to use a shortcut when calling the method.
Unrelated, you can drastically shorten your method:
public static int addTwoEach(params int[] args) { return args.Sum() + 2 * args.Length; }
Using params
allows you to call the function with no arguments. Without params
:
static public int addTwoEach(int[] args) { int sum = 0; foreach (var item in args) { sum += item + 2; } return sum; } addtwoEach(); // throws an error
Compare with params
:
static public int addTwoEach(params int[] args) { int sum = 0; foreach (var item in args) { sum += item + 2; } return sum; } addtwoEach(); // returns 0
Generally, you can use params when the number of arguments can vary from 0 to infinity, and use an array when numbers of arguments vary from 1 to infinity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With