What is the params keyword in C#?
The params keyword
C# provides the params keyword to define a method parameter that can take a variable number of arguments.
Since there may be instances where a developer is not entirely sure of the number of arguments a method should have, the developer can use the params keyword to see if the caller can call our method with one or two or multiple arguments.
We can pass multiple arguments for the params parameter, and the compiler will change these arguments to a
Therefore, the params parameter results in cleaner code, as we do not need to provide multiple overloads of a method.
With the
paramskeyword for a method argument, the caller can pass an array of values or a comma-separated list of values in the function.
Some important notes
- The
paramskeyword marks the final argument in the method, so no other parameters can be added after using theparamskeyword in a method declaration.
//Invalid-params should be the last parameter
public int Sum(params int[] numbers, char input)
- There can only be one
paramskeyword argument in a method.
//Invalid- only one params is allowed
public int Sum(params int[] numbers, params int[] inputValues)
- A compiler time error is shown if the declared type of
paramsparameter is not a one-dimensional array.
Calling the params method
The caller can call a method with a params parameter, with:
- An array of arguments of the specified type.
- A comma-separated argument list of the type of the array elements.
- We can skip passing the arguments and keep the argument list empty.
In the code sample below, we have created a function with the params parameter and called it with two arguments, five arguments, and an array of numbers. The function sums all the numbers passed and returns the total sum as the output.
Sum of numbers is 9
Sum of numbers is 15
Sum of Array of nums is 49
Code
using System;namespace Hello{class ParamsTest{static void Main(string[] args){int twoSum = SumNumbers(4,5);Console.WriteLine("Sum of numbers is {0}",twoSum);int fiveSum = SumNumbers(1, 2, 3, 4, 5);Console.WriteLine("Sum of numbers is {0}",fiveSum);int[] nums = { 2,5,3,4,5,6,7,8,9};int arraySum = SumNumbers(nums);Console.WriteLine("Sum of Array of nums is {0}",arraySum);}public static int SumNumbers(params int[] numbers){int totalSum = 0;foreach (int number in numbers){totalSum += number;}return totalSum;}}}