(This feature is not available in .NET Framework or .NET Standard 2.0 and below.)
In C# 13 one can use a collection type instead of an array for open parameters in a method.
// Before
public void Foo<T>(params T[] items)
{
}
// After
using System;
public void Foo<T>(params ReadOnlySpan<T> items)
{
}The benefits of this change is a better handling of null for the parameter, and performance.
By replacing params params T[] with params ReadOnlySpan<T> one ensures null is not a concern anymore, since ReadOnlySpan<T> is a ref struct, and the burden of the check is moved to the caller.
If the method must not be changed because it's a public API, create an override using params ReadOnlySpan<T>, and unify the two methods. The compiler will choose the best override seamlessly.
Diagnostic CSL1011 is emitted under the following conditions:
- The
paramsparameter is an array. - The method does not already have an override with
params ReadOnlySpan<T>. - The method is not
async(until the language supports it). - This parameter is used in the method.
public static int Foo<T>(params T[] items) // CSL1011: Implement params collection.
{
return items.Length;
}