Skip to content

Allow params to use collections C# 13.0code reductionperformance

The params keyword no longer has to use an array but can use other collection types.

The params modifier keyword could only take the supplied arguments and put them into an array.

With C# 13 the params keyword can now be used with other collection types such as List<T>, Span<T>, IEnumerable<T> etc.

Code ​

csharp
var results = SquareList(1, 2, 3, 4, 5);
var total = Sum(1, 2, 3, 4, 5); // No array is allocated

List<int> SquareList(params List<int> numbers)
  => numbers.ConvertAll(x => x * x);

int Sum(params ReadOnlySpan<int> numbers)
{
    var sum = 0;
    foreach (var n in numbers)
        sum += n;
    return sum;
}
csharp
var results = SquareList(1, 2, 3, 4, 5);
var total = Sum(1, 2, 3, 4, 5); // Allocates an array on every call

List<int> SquareList(params int[] numbers)
  => new List<int>(numbers).ConvertAll(x => x * x);

int Sum(params int[] numbers)
{
    var sum = 0;
    foreach (var n in numbers)
        sum += n;
    return sum;
}

Notes ​

  • If you specify an interface type, the compiler will choose an appropriate collection type to use.
  • params ReadOnlySpan<T> and params Span<T> let the compiler pass the arguments without allocating an array.

More information ​

Powered by Intracia