How to Use Params Keyword in C# for Variable Arguments
In C#, the
params keyword allows a method to accept a variable number of arguments as an array. You declare it before the last parameter in the method signature, enabling callers to pass zero or more arguments without explicitly creating an array.Syntax
The params keyword is used before the last parameter of a method to indicate it can take any number of arguments of a specified type. This parameter is treated as an array inside the method.
- params: keyword to allow variable arguments
- type[]: the type of elements in the array
- parameterName: the name used inside the method
csharp
void MethodName(params int[] numbers) { // method body }
Example
This example shows a method that sums any number of integers passed to it using params. You can call it with zero, one, or many arguments.
csharp
using System; class Program { static void SumNumbers(params int[] numbers) { int sum = 0; foreach (int num in numbers) { sum += num; } Console.WriteLine($"Sum: {sum}"); } static void Main() { SumNumbers(1, 2, 3); // Output: Sum: 6 SumNumbers(10, 20); // Output: Sum: 30 SumNumbers(); // Output: Sum: 0 } }
Output
Sum: 6
Sum: 30
Sum: 0
Common Pitfalls
Common mistakes when using params include:
- Placing the
paramsparameter anywhere but last in the method signature causes a compile error. - Trying to use more than one
paramsparameter in a method is not allowed. - Passing an explicit array or individual arguments both work, but mixing types can confuse the compiler.
csharp
/* Wrong: params not last */ // void WrongMethod(params int[] numbers, string name) { } // Error /* Correct: params last */ void CorrectMethod(string name, params int[] numbers) { } /* Wrong: two params parameters */ // void AnotherWrong(params int[] nums, params string[] texts) { } // Error /* Correct usage */ void AnotherCorrect(params int[] nums) { }
Quick Reference
Tips for using params keyword:
- Only one
paramsparameter allowed per method. - It must be the last parameter in the method signature.
- Inside the method, the
paramsparameter is treated as an array. - You can call the method with zero or more arguments without creating an array explicitly.
Key Takeaways
Use
params to let a method accept a variable number of arguments as an array.The
params parameter must be the last in the method signature and only one is allowed.You can call the method with zero or many arguments without manually creating an array.
Inside the method, the
params parameter behaves like a normal array.Avoid placing
params anywhere but last to prevent compile errors.