ASP.NET Hosting

ASP.NET 9 : Params Collections

The params keyword only allowed arrays before.NET 9.A method can accept a variable number of arguments of the same data type thanks to a unique kind of parameter called a parameters array. It is declared with the array type after the params keyword.

How does the param work?

  1. 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.
  2. 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!