In C# there is a params keyword which allows a method parameter to take variable number of arguments. MSDN
Some notes on param
- It must always be the last parameter in the function/method definition
- There can only be one params keyword in a function/method parameter signature
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
int Sum(int[] args) { int sum = 0; foreach (var item in args) { sum += item; } return sum; } //calling the above Sum method we would call it like int[] array = new int[] {1, 2, 3} int result = Sum(array); |
But by changing it to params we can change the call and simplify it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
int SumWithParams(params int[] args) { int sum = 0; foreach (var item in args) { sum += item; } return sum; } //calling the above SumWithParams woud give us the same result int result = SumWithParams(1, 2, 3); //calling this would not fail either int result = SumWithParams(); //result is 0 |
There is no performance bottleneck in using params because the compiler is basically changing your code into an array for you, thus it is basically just syntactic sugar for C#.
Leave A Comment