Prior to .NET 9, the params keyword supported only arrays.Params array is a special type of parameter that allows a method to accept a variable number of arguments of the same data type. It's declared using the params keyword followed by the array type.
How does the param work?
- Argument Passing
- We can pass any number of arguments of the specified data type to the method.
- These arguments are automatically collected into an array.
- Inside the Method
- The params array is treated like a regular array.
- We can iterate over it, access its elements, and perform operations on it.
Example
static void PrintSumOfNumbers(params int[] numbers)
{
var sum = numbers.Sum();
Console.Write($"Sum of Numbers: {sum}");
}
PrintSumOfNumbers(1, 2, 3, 4, 5);
Output
.NET 9 extends the params keyword to support a wider range of collections, including those used in collection expressions (introduced in .NET 8), beyond traditional arrays.
Example
static void PrintSumOfNumbers(params IEnumerable<int> numbers)
{
var sum = numbers.Sum();
Console.WriteLine($"Sum of numbers : {sum}");
}
PrintSumOfNumbers(1, 2, 3, 4, 5);
PrintSumOfNumbers(new[] { 1, 2, 3, 4, 5 });
PrintSumOfNumbers(new List<int> { 1, 2, 3, 4, 5 });
Here, PrintSumOfNumbers demonstrates the params keyword's flexibility with IEnumerable. It's called with comma-separated values, integer arrays, and List<int> instances.
Output
A notable feature of params collections is their seamless integration with Span<T> and ReadOnlySpan<T>. This enables efficient memory utilization and reduces overhead, contributing to improved performance.
Example
static void PrintSumOfNumbers(params ReadOnlySpan<int> numbers)
{
var sum = 0;
foreach (var number in numbers)
{
sum += number;
}
Console.WriteLine($"Sum of numbers: {sum}");
}
var numbers = new int[] { 1, 2, 3, 4, 5 };
PrintSumOfNumbers(numbers);
Output
Param collections can accelerate your applications, even without direct code changes, as the .NET runtime can now employ high-performance types like Span<T> in more scenarios. The familiar params syntax remains unchanged, offering callers greater flexibility in method invocation while the compiler efficiently selects the appropriate overload.
Happy Coding!