C#idiomatic C#
ca1861fundamentals/code-analysis/quality-rules

Code analysis

CA1861: Avoid constant arrays as arguments

Learn about code analysis rule CA1861: Avoid constant arrays as arguments

CA1861 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

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.

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:

csharp
// A method argument
string message = string.Join(" ", new[] { "Hello", "world!" });
vb
' 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.

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

private string GetMessage()
{
    return string.Join(" ", array);
}
vb
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 runtime, 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.

csharp
#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.

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

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