Avoid constant arrays as arguments
Avoid constant arrays as arguments
Microsoft docsDescription
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. 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.
Cause
A constant array of literal values is passed to a method via regular invocation or extension method invocation.
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:
The following example show how the violation of this rule is fixed by extracting the argument to a static readonly field.
Now, the value of the array is resolved at compile time rather than at runtime, making code more performant.
Example
// A method argument
string message = string.Join(" ", new[] { "Hello", "world!" });When to suppress
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.