Редагувати

Поділитися через


CA1861: Avoid constant arrays as arguments

Property Value
Rule ID CA1861
Title Avoid constant arrays as arguments
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As suggestion

Cause

A constant array of literal values is passed to a method via regular invocation or extension method invocation.

Rule description

Constant arrays passed as arguments are not reused when called repeatedly, which implies a new array is created each time. If the passed array is not mutated within the called method, consider extracting it to a static readonly field to improve performance.

Note

If the called method mutates the passed array or if you're not sure if the method would mutate the array, don't extract the array to a static readonly field. Doing so could be a breaking change. In this case, it's better to suppress the warning instead.

How to fix violations

Extract constant arrays to static readonly fields if the passed array is not mutated within the called method.

The following example shows a violation of the rule:

// A method argument
string message = string.Join(" ", new[] { "Hello", "world!" });
' A method argument
Dim message As String = String.Join(" ", {"Hello", "world!"})

The following example show how the violation of this rule is fixed by extracting the argument to a static readonly field.

private static readonly string[] array = new[] { "Hello" , "world!" };

private string GetMessage()
{
    return string.Join(" ", array);
}
Private Shared ReadOnly array As String() = {"Hello", "world!"}

Private Function GetMessage() As String
    Return String.Join(" ", array)
End Function

Now, the value of the array is resolved at compile time rather than at run time, making code more performant.

When to suppress warnings

Suppress a violation of this rule if:

  • The invocation only runs once.
  • The array could be mutated within the invoked method, or you aren't sure if it would mutated.
  • You're not concerned about the performance impact of creating a constant array for each invocation.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1861
// The code that's violating the rule is on this line.
#pragma warning restore CA1861

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1861.severity = none

For more information, see How to suppress code analysis warnings.