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?
- 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
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
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
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!